Shift Method in JavaScript | Advanced Guide

Shift Method in Javascript

Learn what is shift method in javascript.

Shift() Method

It removes the element at the beginning of the array. And it returns the element.

Syntax:

arrayname.shift():*

where:

*: indicates the first element in the array

Example code:

var fruits = ["Apple", "Orange", "banana", "Grapes", "Watermelon"];

document.write(fruits.shift(), "<br/>"); // print first element in the array, "Apple" then removes it
document.write(fruits);

Output:

shift method in javascript

Steps:

  1. Here we have created an array of “fruits” and assigned a list of values inside the square bracket.
  2. If you want to remove and return the first element of an array, then you should use the “shift()” method in javascript. We print the “friuits.shift()”, so it returns the first element Apple and removes.

Leave a Reply