What is JavaScript Shift?


Introduction

In this article, we cover the Shift function in Javascript, we also talk about its implementations, Use-cases, and limitations of using Javascript Shift.

Table of Contents

  • What is Javascript Shift?
  • Where would you use JavaScript Shift?
  • Code and its explanation
  • Limitations and caveats
  • Other Related Concepts

What is Javascript Shift?

Before we dive into the concept, let’s take a step back and understand what is Javascript shift. Javascript Shift is an inbuilt Array method that removes the first element from an array and returns the removed element.

By doing so, the element in the zeroth index is removed and the items in the consecutive indexes are moved forward.

Eg: In arr = [ “a”,”b”,”c”] after Shift is used the element “a” is removed and the subsequent elements are moved up 1 index, i.e “b” whose index was 1 initially is moved to 0

Subsequently, the Javascript Shift() function reduces the size of the array by 1. And on the contrary, the Unshift function is used to remove the last element.

Syntax of Javascript Shift function

array.shift()

Where array refers to the name of the string.


Where would you use JavaScript Shift?

The JavaScript Shift() function can be used in multiple instances, however, the most common use-case is while dealing with sorted arrays where the first element must be removed and stored in an object.

Ex: You’re dealing with an array that’s sorted based on a parameter say point, and now you want the first element to be removed from the array. Javascript shift works best here as it removes the first character ensuring he doesn’t participate again and also returns the element so that it can be stored for reference.

Code and its explanation:

//implementation of javascript shift function
var fruits = ["Apple", "Mango", "Oranges", "Banana"];
var shifted = fruits.shift();

console.log(fruits);
//array after Javascript Shift was used
// [ "Mango", "Oranges", "Banana" ]

console.log(shifted);
//Element that was retuned
//Apple


Limitations and caveats

  • The Shift function returns undefined if the array is empty
  • The Javascript Shift method is not a pure function as it directly modifies the array
  • The Javascript Shift function can only be used to remove the first element