The Array.shift() method in vanilla JS

Today, I wanted to talk about the Array.shift() method. This is a quick one.
The Array.shift() method removes the first item from an array and returns it. The array is modified.
let wizards = [‘Gandalf’, ‘Radagast’, ‘Merlin’]; let first = wizards.shift(); // logs “Gandalf” console.log(first); // logs [“Radagast”, “Merlin”] console.log(wizards); Here’s a demo.
If you only need to get the first item in the array, you’re probably better off using bracket notation, like this.


This content originally appeared on Go Make Things and was authored by Go Make Things

Today, I wanted to talk about the Array.shift() method. This is a quick one.

The Array.shift() method removes the first item from an array and returns it. The array is modified.

let wizards = ['Gandalf', 'Radagast', 'Merlin'];
let first = wizards.shift();

// logs "Gandalf"
console.log(first);

// logs ["Radagast", "Merlin"]
console.log(wizards);

Here’s a demo.

If you only need to get the first item in the array, you’re probably better off using bracket notation, like this.

let first = wizards[0];

The Array.shift() method is most useful when you want to actually remove the first item from the original array and modify its length.


This content originally appeared on Go Make Things and was authored by Go Make Things


Print Share Comment Cite Upload Translate Updates
APA

Go Make Things | Sciencx (2021-03-02T15:30:00+00:00) The Array.shift() method in vanilla JS. Retrieved from https://www.scien.cx/2021/03/02/the-array-shift-method-in-vanilla-js/

MLA
" » The Array.shift() method in vanilla JS." Go Make Things | Sciencx - Tuesday March 2, 2021, https://www.scien.cx/2021/03/02/the-array-shift-method-in-vanilla-js/
HARVARD
Go Make Things | Sciencx Tuesday March 2, 2021 » The Array.shift() method in vanilla JS., viewed ,<https://www.scien.cx/2021/03/02/the-array-shift-method-in-vanilla-js/>
VANCOUVER
Go Make Things | Sciencx - » The Array.shift() method in vanilla JS. [Internet]. [Accessed ]. Available from: https://www.scien.cx/2021/03/02/the-array-shift-method-in-vanilla-js/
CHICAGO
" » The Array.shift() method in vanilla JS." Go Make Things | Sciencx - Accessed . https://www.scien.cx/2021/03/02/the-array-shift-method-in-vanilla-js/
IEEE
" » The Array.shift() method in vanilla JS." Go Make Things | Sciencx [Online]. Available: https://www.scien.cx/2021/03/02/the-array-shift-method-in-vanilla-js/. [Accessed: ]
rf:citation
» The Array.shift() method in vanilla JS | Go Make Things | Sciencx | https://www.scien.cx/2021/03/02/the-array-shift-method-in-vanilla-js/ |

Please log in to upload a file.




There are no updates yet.
Click the Upload button above to add an update.

You must be logged in to translate posts. Please log in or register.