JavaScript Arrays
What is an Array?
An array is a special variable, which can hold more than one value at a time. It is a collection of elements stored in a single variable.
Creating an Array
There are multiple ways to create an array in JavaScript:
-
Using an array literal:
let fruits = ["Apple", "Banana", "Cherry"]; console.log(fruits); // ["Apple", "Banana", "Cherry"]
-
Using the
Array
constructor:let fruits = new Array("Apple", "Banana", "Cherry"); console.log(fruits); // ["Apple", "Banana", "Cherry"]
Accessing Array Elements
You can access elements of an array by their index:
let fruits = ["Apple", "Banana", "Cherry"];
console.log(fruits[0]); // "Apple"
console.log(fruits[1]); // "Banana"
console.log(fruits[2]); // "Cherry"
Modifying Array Elements
You can modify elements of an array by their index:
let fruits = ["Apple", "Banana", "Cherry"];
fruits[1] = "Blueberry";
console.log(fruits); // ["Apple", "Blueberry", "Cherry"]
Array Methods
-
push()
Adds new elements to the end of an array:
let fruits = ["Apple", "Banana"]; fruits.push("Cherry"); console.log(fruits); // ["Apple", "Banana", "Cherry"]
-
pop()
Removes the last element of an array:
let fruits = ["Apple", "Banana", "Cherry"]; let lastFruit = fruits.pop(); console.log(fruits); // ["Apple", "Banana"] console.log(lastFruit); // "Cherry"
-
shift()
Removes the first element of an array:
let fruits = ["Apple", "Banana", "Cherry"]; let firstFruit = fruits.shift(); console.log(fruits); // ["Banana", "Cherry"] console.log(firstFruit); // "Apple"
-
unshift()
Adds new elements to the beginning of an array:
let fruits = ["Banana", "Cherry"]; fruits.unshift("Apple"); console.log(fruits); // ["Apple", "Banana", "Cherry"]
-
length
Returns the length of an array:
let fruits = ["Apple", "Banana", "Cherry"]; console.log(fruits.length); // 3
-
concat()
Joins two or more arrays:
let fruits = ["Apple", "Banana"]; let moreFruits = ["Cherry", "Date"]; let allFruits = fruits.concat(moreFruits); console.log(allFruits); // ["Apple", "Banana", "Cherry", "Date"]
-
slice()
Returns selected elements in an array, as a new array:
let fruits = ["Apple", "Banana", "Cherry", "Date"]; let someFruits = fruits.slice(1, 3); console.log(someFruits); // ["Banana", "Cherry"]
-
splice()
Adds/removes elements from an array:
let fruits = ["Apple", "Banana", "Cherry"]; fruits.splice(1, 1, "Blueberry", "Kiwi"); console.log(fruits); // ["Apple", "Blueberry", "Kiwi", "Cherry"]
-
forEach()
Calls a function once for each array element:
let fruits = ["Apple", "Banana", "Cherry"]; fruits.forEach(function(fruit) { console.log(fruit); }); // Output: // "Apple" // "Banana" // "Cherry"
-
map()
Creates a new array with the result of calling a function for every array element:
let numbers = [1, 2, 3]; let squaredNumbers = numbers.map(function(number) { return number * number; }); console.log(squaredNumbers); // [1, 4, 9]