menu

JavaScript/Typescript - 16 Topics

DEEP DIVE INTO

JavaScript/Typescript

Topic:shift() Method

menu

In JavaScript, the shift() method removes the first element from an array and returns that element. It modifies the original array by removing the first item, and if the array is empty, it will return undefined.

Here's the basic syntax of the shift() method:

javascriptconst removedElement = array.shift();
  • array: The array from which you want to remove the first element.

  • removedElement: The element that was removed from the array.

Here's an example of how shift() works:

javascriptconst fruits = ['apple', 'banana', 'cherry'];

const firstFruit = fruits.shift();

console.log(fruits);      // Outputs: ['banana', 'cherry']
console.log(firstFruit);  // Outputs: 'apple' (the removed element)

In this example, the shift() method removes the first element ('apple') from the fruits array and assigns it to the firstFruit variable.

The shift() method is commonly used when you want to remove and retrieve elements from the beginning of an array, effectively shifting all remaining elements to lower indices.

1280 x 720 px