Arrays in JavaScript are special objects used to store multiple values in a single variable. They allow you to group related data together and provide various methods to manipulate the collection efficiently. Arrays are zero-indexed, meaning the first element has an index of 0
.
- Dynamic Size: Arrays in JavaScript can grow or shrink dynamically as elements are added or removed.
- Mixed Data Types: An array can hold elements of different data types, such as numbers, strings, objects, or even other arrays.
- Indexed Access: Elements in an array can be accessed using their numeric index.
There are two main ways to create arrays in JavaScript:
- Using Array Literal Syntax:
const fruits = ["Apple", "Banana", "Cherry"];
- Using the
Array
Constructor:const numbers = new Array(1, 2, 3, 4);
You can access elements using their index:
const fruits = ["Apple", "Banana", "Cherry"];
console.log(fruits[0]); // Output: Apple
-
push()
- Adds an element to the end of the array.const fruits = ["Apple", "Banana"]; fruits.push("Cherry"); console.log(fruits); // ["Apple", "Banana", "Cherry"]
-
pop()
- Removes the last element from the array.const fruits = ["Apple", "Banana", "Cherry"]; fruits.pop(); console.log(fruits); // ["Apple", "Banana"]
-
shift()
- Removes the first element of the array.const fruits = ["Apple", "Banana", "Cherry"]; fruits.shift(); console.log(fruits); // ["Banana", "Cherry"]
-
unshift()
- Adds an element to the beginning of the array.const fruits = ["Banana", "Cherry"]; fruits.unshift("Apple"); console.log(fruits); // ["Apple", "Banana", "Cherry"]
-
slice()
- Returns a shallow copy of a portion of the array.const fruits = ["Apple", "Banana", "Cherry", "Date"]; const citrus = fruits.slice(1, 3); console.log(citrus); // ["Banana", "Cherry"]
-
splice()
- Modifies the contents of an array by adding, removing, or replacing elements.const fruits = ["Apple", "Banana", "Cherry"]; fruits.splice(1, 1, "Mango"); console.log(fruits); // ["Apple", "Mango", "Cherry"]
-
map()
- Creates a new array by applying a function to each element.const numbers = [1, 2, 3]; const squares = numbers.map((num) => num * num); console.log(squares); // [1, 4, 9]
-
filter()
- Creates a new array with elements that pass a test.const numbers = [1, 2, 3, 4]; const even = numbers.filter((num) => num % 2 === 0); console.log(even); // [2, 4]
-
reduce()
- Reduces an array to a single value.const numbers = [1, 2, 3, 4]; const sum = numbers.reduce((acc, num) => acc + num, 0); console.log(sum); // 10
JavaScript arrays can hold other arrays, creating a multidimensional array:
const matrix = [
[1, 2, 3],
[4, 5, 6],
[7, 8, 9],
];
console.log(matrix[1][2]); // Output: 6
Arrays are a fundamental data structure in JavaScript that offer flexibility and efficiency in handling collections of data. Their extensive built-in methods make them powerful tools for developers to perform various operations.