a - arrays introduction Arrays in JavaScript are used to store multiple values in a single variable. They are fundamental in organizing and managing data in a list-like structure. Arrays are versatile and used to store ordered lists of elements. You can add, remove, and update elements using various methods. Arrays support iteration with for, for...of, and .forEach(). Use array methods like .map(), .filter(), and .reduce() for functional transformations. Be mindful of common pitfalls, such as undefined elements and improper iteration.
b - Create an array and access its elements There are several ways to declare and initialize arrays in JavaScript: 1. Using Array Literal (Preferred) 2. Using the Array Constructor const numbers = new Array(10) β Creates an array with 10 empty slots const names = new Array('Alice', 'Bob', 'Charlie'); βCreates an array with 'Alice', 'Bob', 'Charlie' Accessing Array Elements: Arrays are zero-indexed, meaning the first element is at index 0. console.log(fruits[2]); β prints the 3rd element of the array console.log(fruits[fruits.length - 1]); β prints the last element of the array
c - Modify array elements You can update or remove elements from an array using various methods: fruits[1] = 'mango'; β Update an Element delete fruits[1]; β Remove an Element but not recommended fruits.pop(); β Remove Last Element fruits.shift(); β Remove First Element fruits.push('orange'); β Add to End fruits.unshift('grape'); β Add to Beginning
d - Iterating Over an Array, length and features There are multiple ways to loop through an array: Using a for Loop Using for...of Loop Using forEach() Method length property and features length: Returns the number of elements in the array. console.log(fruits.length) Dynamic Size: Arrays can expand or shrink as needed. Can Hold Mixed Data Types:
e - built-in methods push(): Adds one or more elements to the end β arr.push('new') pop(): Removes the last element β arr.pop() shift(): Removes the first element β arr.shift() unshift(): Adds elements to the beginning β arr.unshift('first') slice(): Returns a shallow copy of a portion β arr.slice(1, 3) splice(): Changes contents by adding/removing elements β arr.splice(1, 1, 'new') indexOf(): Returns the index of the first match β arr.indexOf('apple') includes(): Checks if an element exists β arr.includes('apple') join(): Joins array elements into a string β arr.join(', ') map(): Creates a new array with transformed values β arr.map(x => x.toUpperCase()) filter(): Creates a new array with filtered elements β arr.filter(x => x.length > 5) reduce(): Reduces an array to a single value β arr.reduce((a, b) => a + b, 0)