Javascript Array shift()

Introduction

Javascript array shift() method removes the first element from an array.

It returns that removed element.

This method changes the array length.

Javascript Array pop() removes the last element in an array.

arr.shift()

Remove the first item of an array:

var languages = ["CSS", "HTML", "Java", "Javascript"];
console.log(languages);/*  w  ww  .  j  a  va  2 s.com*/

languages.shift();
console.log(languages);

Removing an element from an array

var languages = ['CSS', 'Java', 'HTML', 'Javascript'];

console.log('languages before:', JSON.stringify(languages));

var shifted = languages.shift(); 

console.log('languages after:', languages); 
console.log('Removed this element:', shifted); 

Using shift() method in while loop

var names = ["CSS", "Java", "HTML", "Javascript" ,"C++"];

while( (i = names.shift()) !== undefined ) {
   console.log(i);//w ww. ja va2 s. c o m
}
console.log(names);

More example

let colors = new Array(); // create an array 
let count = colors.push("red", "green"); // push two items 
console.log(count); // 2 

count = colors.push("black"); // push another item on 
console.log(count); // 3 

let item = colors.shift(); // get the first item 
console.log(item); // "red" 
console.log(colors.length); // 2 



PreviousNext

Related