Push, Pop, Shift and Unshift Array Methods in JavaScript

js.Srijan

Table of Contents

Introduction

In this article, we will learn about four array methods i.e. push(), pop(), shift() and unshift() which allow us to add and remove elements from beginning and end of an array.

push(): Add elements to the end of an Array

Array Push

Using push() we can add elements to the end of an array.

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

push() returns length of the new array.

let arr = [ 1, 2, 3, 4 ]; let arrLength = arr.push( 5, 6, 7 ); console.log(arrLength); // 7

pop(): Remove an element from end of an Array

Array Pop

Pop remove the last element in an Array.

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

pop() returns the removed element.

let arr = [ 1, 2, 3, 4 ]; let removedElement = arr.pop(); console.log(removedElement); // 4

shift(): Remove an Element from the front of an Array

Array Shift

Shift remove the first element in an Array.

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

shift() returns the removed element from the array.

let arr = [ 0, 1, 2, 3 ]; let removedElement = arr.shift(); console.log(removedElement); // 0

unshift(): Add elements to the front of an Array

Array Unshift

Using unshift() we can add elements to the front of an array.

let arr = [ 1, 2, 3 ]; arr.unshift(0); console.log(arr); // [ 0, 1, 2, 3 ]

unshift() returns length of the new array.

let arr = [ 4, 5, 6 ]; let arrLength = arr.unshift( 0, 1, 2, 3 ); console.log(arrLength); // 7

Share this

Share on social media