DEV Community

Murtaja Ziad
Murtaja Ziad

Posted on • Originally published at blog.murtajaziad.xyz on

5 array methods in JavaScript.

Arrays are used to store multiple values in a single variable, and here’s 5 methods for them.


1. push()

push() method adds one or more elements to the end of an array and returns the new length of the array.

const animals = ["pigs", "goats", "sheep"];

const count = animals.push("cows");
console.log(count); // 4
console.log(animals); // ["pigs", "goats", "sheep", "cows"]
Enter fullscreen mode Exit fullscreen mode

2. pop()

pop() method removes the last element from an array and returns that element. This method changes the length of the array.

const plants = ["broccoli", "cauliflower", "cabbage", "kale", "tomato"];

console.log(plants.pop()); // tomato
console.log(plants); // ["broccoli", "cauliflower", "cabbage", "kale"]

plants.pop();
console.log(plants); // ["broccoli", "cauliflower", "cabbage"]
Enter fullscreen mode Exit fullscreen mode

3. shift()

shift() method removes the first element from an array and returns that removed element. This method changes the length of the array.

const array1 = [1, 2, 3];

const firstElement = array1.shift();
console.log(array1); // [2, 3]
console.log(firstElement); // 1
Enter fullscreen mode Exit fullscreen mode

4. reverse()

reverse() method reverses an array in place. The first array element becomes the last, and the last array element becomes the first be careful, as it changes the original array.

const array1 = ["one", "two", "three"];
console.log(array1); // ["one", "two", "three"]

const reversed = array1.reverse();
console.log(reversed); // ["three", "two", "one"]
console.log(array1); // ["three", "two", "one"]
Enter fullscreen mode Exit fullscreen mode

5. find()

find() method returns the value of the first element in the provided array that satisfies the provided testing function.

const array1 = [5, 12, 8, 130, 44];
const found = array1.find(element => element > 10);

console.log(found); // 12
Enter fullscreen mode Exit fullscreen mode

Top comments (0)