JavaScript arrays come with a variety of built-in methods that make it easy to manipulate arrays and perform common operations efficiently. Here are some of the most commonly used array methods:
Adds one or more elements to the end of an array and returns the new length of the array.
let fruits = ['apple', 'banana'];
fruits.push('orange');
console.log(fruits); // Output: ['apple', 'banana', 'orange']
Removes the last element from an array and returns that element.
let fruits = ['apple', 'banana', 'orange'];
let removed = fruits.pop();
console.log(removed); // Output: 'orange'
console.log(fruits); // Output: ['apple', 'banana']
Removes the first element from an array and returns that element, shifting all subsequent elements one position to the left.
let fruits = ['apple', 'banana', 'orange'];
let removed = fruits.shift();
console.log(removed); // Output: 'apple'
console.log(fruits); // Output: ['banana', 'orange']
Adds one or more elements to the beginning of an array and returns the new length of the array.
let fruits = ['banana', 'orange'];
fruits.unshift('apple');
console.log(fruits); // Output: ['apple', 'banana', 'orange']
Returns a new array that combines the elements of the original array with other arrays or values.
let fruits = ['apple', 'banana'];
let moreFruits = fruits.concat(['orange', 'grape']);
console.log(moreFruits); // Output: ['apple', 'banana', 'orange', 'grape']
Returns a shallow copy of a portion of an array into a new array object.
let fruits = ['apple', 'banana', 'orange', 'grape'];
let citrus = fruits.slice(2);
console.log(citrus); // Output: ['orange', 'grape']
Changes the contents of an array by removing or replacing existing elements and/or adding new elements in place.
let fruits = ['apple', 'banana', 'orange', 'grape'];
fruits.splice(2, 1, 'mango');
console.log(fruits); // Output: ['apple', 'banana', 'mango', 'grape']
These are just a few of the many array methods available in JavaScript. Each method offers different functionalities, making it easy to perform various array operations efficiently in your JavaScript code.