JavaScript Array Methods

Array Methods:

JavaScript arrays have many built-in methods for performing common tasks, such as push(), pop(), shift(), unshift(), splice(), concat(), slice(), indexOf(), includes(), filter(), map(), and many more. These methods make it easy to manipulate and work with arrays efficiently in JavaScript.

JavaScript provides a variety of built-in methods that can be used to manipulate arrays efficiently. Here’s an overview of some commonly used array methods:

  1. push(): Adds one or more elements to the end of an array and returns the new length of the array.
let fruits = ['apple', 'banana', 'orange'];
fruits.push('kiwi');
console.log(fruits); // Output: ['apple', 'banana', 'orange', 'kiwi']
  1. pop(): Removes the last element from an array and returns that element.
let fruits = ['apple', 'banana', 'orange'];
let lastFruit = fruits.pop();
console.log(lastFruit); // Output: 'orange'
console.log(fruits);    // Output: ['apple', 'banana']
  1. shift(): Removes the first element from an array and returns that element.
let fruits = ['apple', 'banana', 'orange'];
let firstFruit = fruits.shift();
console.log(firstFruit); // Output: 'apple'
console.log(fruits);     // Output: ['banana', 'orange']
  1. unshift(): 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']
  1. concat(): Combines two or more arrays and returns a new array.
let fruits = ['apple', 'banana'];
let moreFruits = ['orange', 'kiwi'];
let allFruits = fruits.concat(moreFruits);
console.log(allFruits); // Output: ['apple', 'banana', 'orange', 'kiwi']
  1. slice(): Returns a shallow copy of a portion of an array into a new array.
let fruits = ['apple', 'banana', 'orange', 'kiwi'];
let citrus = fruits.slice(1, 3);
console.log(citrus); // Output: ['banana', 'orange']
  1. splice(): Adds or removes elements from an array.
let fruits = ['apple', 'banana', 'orange', 'kiwi'];
fruits.splice(2, 1, 'grape', 'pineapple');
console.log(fruits); // Output: ['apple', 'banana', 'grape', 'pineapple', 'kiwi']

Each method serves a specific purpose, making array manipulation tasks more convenient and efficient.