JavaScript Code


JavaScript Array shift()


shift() – Remove First Element

array1.shift()
  • array1 is an array which has to be shifted

shift() method removes the first element from the array array1 and returns that removed element. shift() method modifies the original array array1

Examples

1. shift the given array

const array1 = ['apple', 'banana', 'cherry'];
console.log('Original Array  : ' + array1);

const removedElement = array1.shift();
console.log('Removed Element : ' + removedElement);
console.log('Result Array    : ' + array1);

2. shift an empty array

const array1 = [];
console.log('Original Array  : ' + array1);

const removedElement = array1.shift();
console.log('Removed Element : ' + removedElement);
console.log('Result Array    : ' + array1);

if shift() is called on an empty array, then shift() returns undefined


Copyright @2022