DEV Community

Vicky Shinde
Vicky Shinde

Posted on • Edited on

Array methods in JavaScript - Code Vicky

JavaScript provides several built-in methods for working with arrays. Here are some commonly used array methods:

  • push(): Adds one or more elements to the end of an array and returns the new length of the array.
const fruits = ['apple', 'banana']; fruits.push('orange', 'grape'); console.log(fruits); // fruits is now ['apple', 'banana', 'orange', 'grape'] 
Enter fullscreen mode Exit fullscreen mode
  • pop(): Removes the last element from an array and returns that element.
const fruits = ['apple', 'banana', 'orange']; const removedFruit = fruits.pop(); console.log(fruits) // removedFruit is 'orange', fruits is now ['apple', 'banana'] 
Enter fullscreen mode Exit fullscreen mode
  • shift(): Removes the first element from an array and returns that element.
const fruits = ['apple', 'banana', 'orange']; const removedFruit = fruits.shift(); // removedFruit is 'apple', fruits is now ['banana', 'orange'] console.log(fruits); 
Enter fullscreen mode Exit fullscreen mode
  • unshift(): Adds one or more elements to the beginning of an array and returns the new length of the array.
const fruits = ['apple', 'banana', 'orange']; const removedFruit = fruits.shift(); console.log(fruits); // removedFruit is 'apple', fruits is now ['banana', 'orange'] 
Enter fullscreen mode Exit fullscreen mode
  • indexOf(): Returns the first index at which a given element can be found in the array, or -1 if it is not present.
const fruits = ['apple', 'banana', 'orange']; const index = fruits.indexOf('banana'); console.log(index); // index is 1 
Enter fullscreen mode Exit fullscreen mode
  • splice(): Changes the contents of an array by removing or replacing existing elements and/or adding new elements in place.
const fruits = ['apple', 'banana', 'orange']; fruits.splice(1, 1, 'grape', 'kiwi'); console.log(fruits); // fruits is now ['apple', 'grape', 'kiwi', 'orange'] 
Enter fullscreen mode Exit fullscreen mode
  • slice(): Returns a shallow copy of a portion of an array into a new array.
const fruits = ['apple', 'banana', 'orange', 'grape']; const slicedFruits = fruits.slice(1, 3); console.log(slicedFruits); // slicedFruits is ['banana', 'orange'], fruits remains unchanged 
Enter fullscreen mode Exit fullscreen mode
  • forEach(): Executes a provided function once for each array element.
const fruits = ['apple', 'banana', 'orange']; fruits.forEach((fruit) => { console.log(fruit); }); console.log(fruits); // Outputs: apple, banana, orange 
Enter fullscreen mode Exit fullscreen mode

These are just a few examples, and JavaScript provides many more array methods for various operations. Understanding these methods can make it easier to work with arrays in JavaScript.

Top comments (0)