JavaScript arrays are used to store multiple values in a single variable. An array is an ordered collection of data items, where each item has a unique index. In JavaScript, arrays are zero-indexed, meaning the first element is at index 0, the second element is at index 1, and so on.
JavaScript provides many methods and functions to work with arrays, such as creating arrays, adding and removing elements, sorting arrays, and iterating over arrays.
Creating Arrays To create an array in JavaScript, use the array literal syntax, which is a set of square brackets containing the values you want to store:
javascriptconst myArray = [1, 2, 3, 4, 5];
You can also create an empty array and add elements later using the push() method:
javascriptconst myArray = [];
myArray.push(1);
myArray.push(2);
myArray.push(3);
Array Methods and Functions JavaScript arrays have many built-in methods and functions that you can use to manipulate arrays. Here are some of the most commonly used ones:
- push(): Adds one or more elements to the end of an array and returns the new length of the array.
javascriptconst myArray = [1, 2, 3];
myArray.push(4);
console.log(myArray); // Output: [1, 2, 3, 4]
- pop(): Removes the last element from an array and returns that element.
javascriptconst myArray = [1, 2, 3];
const lastElement = myArray.pop();
console.log(lastElement); // Output: 3
- unshift(): Adds one or more elements to the beginning of an array and returns the new length of the array.
javascriptconst myArray = [2, 3, 4];
myArray.unshift(1);
console.log(myArray); // Output: [1, 2, 3, 4]
- shift(): Removes the first element from an array and returns that element.
javascriptconst myArray = [1, 2, 3];
const firstElement = myArray.shift();
console.log(firstElement); // Output: 1
- splice(): Adds or removes elements from an array at a specified index.
javascriptconst myArray = [1, 2, 3];
myArray.splice(1, 1); // Remove element at index 1
console.log(myArray); // Output: [1, 3]
myArray.splice(1, 0, 2); // Add element 2 at index 1
console.log(myArray); // Output: [1, 2, 3]
- concat(): Joins two or more arrays and returns a new array.
javascriptconst myArray1 = [1, 2];
const myArray2 = [3, 4];
const newArray = myArray1.concat(myArray2);
console.log(newArray); // Output: [1, 2, 3, 4]
- slice(): Returns a portion of an array as a new array.
javascriptconst myArray = [1, 2, 3, 4, 5];
const newArray = myArray.slice(2, 4); // Returns elements at index 2 and 3
console.log(newArray); // Output: [3, 4]
- indexOf(): Returns the index of the first occurrence of a specified element in an array.
javascriptconst myArray = [1, 2, 3, 4, 5];
const index = myArray