JavaScript Glossary - Lesson #15

JavaScript Array .shift() Method

This method takes out the first element from an array and returns it. The shift method mutates the array during this process, reducing its length.

js
[1, 2, 3, 4, 5].shift()
// 1
js
// List of numbers
const list = [10, 20, 30, 40, 50]

// Remove first number
const newList = list.shift()

// Output result
console.log(newList) // 10

This method when called:

  • Removes the element at the beginning of the array.
  • Mutates the parent array reducing the length.
  • Returns the removed element.
js
array.shift()

The method will return the element removed from the array. If the array is empty, it returns undefined.

js
const names = ['Johnny', 'Pete', 'Sammy']
console.log(names.shift());
// output: 'Johnny'
js
// New array
const numbers = ['ten', 'one', 'two', 'three', 'four'];

// Remove the first element
numbers.shift();

// Output result
console.log(numbers); // ["one","two","three","four"]

Want to improve your coding and design skills?

I'm continually researching the best practices and tools for coding.
Join 50,000+ developers looking to make cool stuff.

We value your privacy. 1-click unsubscribe.

Chris Sev

Chris Sev

Chris Sev is the co-founder of Better Dev. Coding better every day. Previously he created Scotch.io which was acquired.

Comments

What did you think of the article? Let us know!
(these comments are powered by GitHub issues and use 0 trackers)