Shifting is equivalent to popping, working on the first element instead of the last.

The shift() method removes the first array element and "shifts" all other elements to a lower index.

Example

const fruits = ["Banana", "Orange", "Apple", "Mango"];
fruits.shift();   // Removes "Banana" from fruits

The shift() method returns the value that was "shifted out":

Example

const fruits = ["Banana", "Orange", "Apple", "Mango"];
let x = fruits.shift();    // x = "Banana"
 

The unshift() method adds a new element to an array (at the beginning), and "unshifts" older elements:

Example

const fruits = ["Banana", "Orange", "Apple", "Mango"];
fruits.unshift("Lemon");    // Adds "Lemon" to fruits
 

The unshift() method returns the new array length.

Example

const fruits = ["Banana", "Orange", "Apple", "Mango"];
fruits.unshift("Lemon");    // Returns 5



Practice Excercise Practice now