Array in JavaScript
In JavaScript, arrays are used to store ordered collections of values. These values can be of any type (numbers, strings, objects, other arrays, etc.). Arrays are one of the most commonly used data structures in JavaScript because they are versatile, easy to work with, and provide several built-in methods to manage and manipulate data.
What is an Array?
An array is an ordered list of values. Each value in the array is called an element and can be accessed by its index (position in the array). JavaScript arrays are zero-indexed, meaning the first element has an index of 0.
Creating an Array
There are a few ways to create arrays in JavaScript:
1. Using Array Literals
The most common way to create an array is by using square brackets []
:
const fruits = ['Apple', 'Banana', 'Cherry'];
2. Using the new Array()
Syntax
You can also create arrays using the Array
constructor, but this is less common:
const fruits = new Array('Apple', 'Banana', 'Cherry');
If you provide a single number as an argument, it creates an array with that many empty slots:
const emptyArray = new Array(3); // Creates an array with 3 empty slots
Accessing and Modifying Array Elements
1. Accessing Elements by Index
You can access an element in an array using its index:
const fruits = ['Apple', 'Banana', 'Cherry'];
console.log(fruits[0]); // Output: Apple
console.log(fruits[1]); // Output: Banana
2. Modifying Elements
You can modify an element by assigning a new value to a specific index:
fruits[1] = 'Blueberry';
console.log(fruits); // Output: ['Apple', 'Blueberry', 'Cherry']
3. Length of Array
The length
property returns the number of elements in an array.
console.log(fruits.length); // Output: 3
Array Methods
JavaScript provides several built-in methods to work with arrays. Here are some of the most commonly used methods:
1. push()
Adds one or more elements to the end of an array and returns the new length of the array.
const fruits = ['Apple', 'Banana'];
fruits.push('Cherry');
console.log(fruits); // Output: ['Apple', 'Banana', 'Cherry']
2. pop()
Removes the last element from an array and returns that element.
const fruits = ['Apple', 'Banana', 'Cherry'];
const removed = fruits.pop();
console.log(fruits); // Output: ['Apple', 'Banana']
console.log(removed); // Output: Cherry
3. shift()
Removes the first element from an array and returns that element.
const fruits = ['Apple', 'Banana', 'Cherry'];
const removed = fruits.shift();
console.log(fruits); // Output: ['Banana', 'Cherry']
console.log(removed); // Output: Apple
4. unshift()
Adds one or more elements to the beginning of an array and returns the new length of the array.
const fruits = ['Banana', 'Cherry'];
fruits.unshift('Apple');
console.log(fruits); // Output: ['Apple', 'Banana', 'Cherry']
5. concat()
Combines two or more arrays and returns a new array.
const fruits = ['Apple', 'Banana'];
const moreFruits = ['Cherry', 'Date'];
const allFruits = fruits.concat(moreFruits);
console.log(allFruits); // Output: ['Apple', 'Banana', 'Cherry', 'Date']
6. slice()
Returns a shallow copy of a portion of an array. You can specify the start and end index (end index is not inclusive).
const fruits = ['Apple', 'Banana', 'Cherry', 'Date'];
const sliced = fruits.slice(1, 3); // From index 1 to 2
console.log(sliced); // Output: ['Banana', 'Cherry']
7. splice()
Adds/removes elements from any position in the array.
Remove elements:
splice(startIndex, numberOfElementsToRemove)
Add elements:
splice(startIndex, 0, newElement1, newElement2, ...)
const fruits = ['Apple', 'Banana', 'Cherry', 'Date'];
fruits.splice(1, 2, 'Blueberry', 'Grapes'); // Starts at index 1, removes 2 elements, and adds 'Blueberry' and 'Grapes'
console.log(fruits); // Output: ['Apple', 'Blueberry', 'Grapes', 'Date']
8. forEach()
Executes a provided function once for each array element.
const fruits = ['Apple', 'Banana', 'Cherry'];
fruits.forEach((fruit, index) => {
console.log(index, fruit);
});
// Output:
// 0 Apple
// 1 Banana
// 2 Cherry
9. map()
Creates a new array populated with the results of calling a provided function on every element in the array.
const fruits = ['Apple', 'Banana', 'Cherry'];
const upperFruits = fruits.map(fruit => fruit.toUpperCase());
console.log(upperFruits); // Output: ['APPLE', 'BANANA', 'CHERRY']
10. filter()
Creates a new array with all elements that pass the test implemented by the provided function.
const numbers = [1, 2, 3, 4, 5, 6];
const evenNumbers = numbers.filter(num => num % 2 === 0);
console.log(evenNumbers); // Output: [2, 4, 6]
11. reduce()
Applies a function against an accumulator and each element to reduce it to a single value.
const numbers = [1, 2, 3, 4];
const sum = numbers.reduce((acc, num) => acc + num, 0);
console.log(sum); // Output: 10
Multi-Dimensional Arrays
Arrays can also hold other arrays, creating multi-dimensional arrays (e.g., 2D arrays).
const matrix = [
[1, 2, 3],
[4, 5, 6],
[7, 8, 9]
];
console.log(matrix[0][1]); // Output: 2 (Accessing element in the first row, second column)
Summary of Key Array Methods
push()
: Adds elements to the end.pop()
: Removes the last element.shift()
: Removes the first element.unshift()
: Adds elements to the beginning.concat()
: Combines two or more arrays.slice()
: Returns a shallow copy of a portion of an array.splice()
: Adds/removes elements at a specific position.forEach()
: Executes a function for each element.map()
: Creates a new array with results from a function.filter()
: Creates a new array with elements that pass a test.reduce()
: Reduces an array to a single value.