How to use shift and unshift method in javascript

Date: 12/12/2019

Introduction:

In this article, we will explain how to use shift() and unshift() to add and remove the elements from the array in javascript.

shift() used to remove the first element of the array.

unshift() is used to add one or more elements to the array.

shift():

syntax:

arr.shift()

Example:

var arr = [100, 289, 760, 430, 290];
var value = arr.shift();

console.log(value);
console.log(arr);

Output:

  • This function prints the removed element of the array
  • If the array is empty it will return undefined
var arr = [];
var value = arr.shift();

console.log(value);
console.log(arr);

unshift() :

syntax:

arr. unshift(ele1,ele2………)

Example

var arr = [838,90,320,410];
console.log(arr.unshift(220,560));
console.log(arr);

Thanks for using pheonix solutions.

Leave a Reply

This website stores cookies on your computer. These cookies are used to provide a more personalized experience and to track your whereabouts around our website in compliance with the European General Data Protection Regulation. If you decide to to opt-out of any future tracking, a cookie will be setup in your browser to remember this choice for one year.

Accept or Deny