Tags
Asked 2 years ago
9 Jun 2021
Views 229
jignesh

jignesh posted

equivalent to push() or pop() for arrays?

equivalent to push() or pop() for arrays?
web-api

web-api
answered Apr 26 '23 00:00

In JavaScript, arrays have several built-in methods that are equivalent to push() and pop():

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


const arr = [1, 2, 3];
arr.push(4, 5);
console.log(arr); // [1, 2, 3, 4, 5]

pop(): removes the last element from an array and returns the removed element.


const arr = [1, 2, 3];
const lastElement = arr.pop();
console.log(lastElement); // 3
console.log(arr); // [1, 2]

Note that there are also several other methods that can be used to add or remove elements from an array:

unshift(): adds one or more elements to the beginning of an array and returns the new length of the array.


const arr = [1, 2, 3];
arr.unshift(4, 5);
console.log(arr); // [4, 5, 1, 2, 3]

shift(): removes the first element from an array and returns the removed element.


const arr = [1, 2, 3];
const firstElement = arr.shift();
console.log(firstElement); // 1
console.log(arr); // [2, 3]

Each of these methods modifies the original array in place and returns the result, so you can use them to chain multiple operations together.
Post Answer