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:
Steps:
- Here we have created an array of “fruits” and assigned a list of values inside the square bracket.
- 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.