shift() Method in JavaScript

JavaScript1 min read
shift() Method in JavaScript
javascriptshift methodarray methods

shift() is a built-in method in JavaScript that removes the first element from an array.

shift() Method in JavaScript

  • shift() is a built-in method in JavaScript that removes the first element from an array.
  • It modifies the original array and returns the removed element. The remaining elements in the array are shifted down to fill the empty space.

Example:

  • Let's take an array playlist, with elements like song-1, song-2, song-3, song-4, and song-5.
let playlist = ['song-1', 'song-2', 'song-3', 'song-4', 'song-5'];

To show all songs in the playlist, use the forEach() method.

let playlist = ['song-1', 'song-2', 'song-3', 'song-4', 'song-5']; playlist.forEach(item => { document.write(item + "<br>"); }); // Output: song-1 song-2 song-3 song-4 song-5

Now, all the songs in the playlist are displayed as song-1, song-2, song-3, song-4, song-5.

  • If you want to play and remove the first song from the playlist, use the shift() method:
let playlist = ['song-1', 'song-2', 'song-3', 'song-4', 'song-5']; let nowPlaying = playlist.shift(); document.write(`<h3>Now Playing: ${nowPlaying}</h3>`); playlist.forEach(item => { document.write(item + "<br>"); }); // Output-1: Now Playing: song-1 // Output-2: song-2 song-3 song-4 song-5

The first song, song-1, is removed from the playlist array and displayed as Now Playing. The remaining songs are song-2, song-3, song-4, song-5.

  • If you want to play another song and remove it from the playlist, use the shift() method again:
let playlist = ['song-2', 'song-3', 'song-4', 'song-5']; let nowPlaying = playlist.shift(); document.write(`<h3>Now Playing: ${nowPlaying}</h3>`); playlist.forEach(item => { document.write(item + "<br>"); }); // Output-1: Now Playing: song-2 // Output-2: song-3 song-4 song-5

Now, song-2 is removed from the playlist array and displayed as Now Playing, and the remaining songs are song-3, song-4, song-5.

  • Using the shift() method we remove and play songs one by one from the beginning of the playlist.