Javascript Array methods (push, pop, shift, unshift, etc.)
JavaScript provides a variety of methods to manipulate arrays. Here are some of the commonly used array methods:
push() method:
The push() method adds one or more elements to the end of an array and returns the new length of the array.
Syntax:
array.push(element1, element2, ..., elementN)
Example:
let fruits = ['apple', 'banana'];
let length = fruits.push('orange', 'peach');
console.log(fruits); // Output: ["apple", "banana", "orange", "peach"]
console.log(length); // Output: 4
pop() method:
The pop() method removes the last element from an array and returns that element.
Syntax:
array.pop()
Example:
let fruits = ['apple', 'banana', 'orange'];
let lastFruit = fruits.pop();
console.log(fruits); // Output: ["apple", "banana"]
console.log(lastFruit); // Output: "orange"
shift() method:
The shift() method removes the first element from an array and returns that element. The remaining elements are shifted to a lower index.
Syntax:
array.shift()
Example:
let fruits = ['apple', 'banana', 'orange'];
let firstFruit = fruits.shift();
console.log(fruits); // Output: ["banana", "orange"]
console.log(firstFruit); // Output: "apple"
unshift() method:
The unshift() method adds one or more elements to the beginning of an array and returns the new length of the array.
Syntax:
array.unshift(element1, element2, ..., elementN)
Example:
let fruits = ['apple', 'banana'];
let length = fruits.unshift('orange', 'peach');
console.log(fruits); // Output: ["orange", "peach", "apple", "banana"]
console.log(length); // Output: 4
splice() method:
The splice() method adds or removes elements from an array. It changes the original array and returns an array containing the removed elements.
Syntax:
array.splice(index, howMany, element1, ..., elementN)
Example:
let fruits = ['apple', 'banana', 'orange', 'peach'];
let removedFruits = fruits.splice(1, 2, 'grape', 'kiwi');
console.log(fruits); // Output: ["apple", "grape", "kiwi", "peach"]
console.log(removedFruits); // Output: ["banana", "orange"]
concat() method:
The concat() method joins two or more arrays and returns a new array.
Syntax:
array1.concat(array2, array3, ..., arrayN)
Example:
let fruits1 = ['apple', 'banana'];
let fruits2 = ['orange', 'peach'];
let fruits3 = ['grape', 'kiwi'];
let allFruits = fruits1.concat(fruits2, fruits3);
console.log(allFruits); // Output: ["apple", "banana", "orange", "peach", "grape", "kiwi"]
slice() method:
The slice() method returns a shallow copy of a portion of an array into a new array object selected from start to end (end not included) where start and end represent the index of items in that array.
Syntax:
array.slice(start, end)
Example:
const arr = [1, 2, 3, 4, 5];
const slicedArr = arr.slice(2, 4);
console.log(slicedArr); // Output: [3, 4]