Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript "shift" versus "splice" - are these statements equal?

Tags:

I just want to confirm if the following two Javascript statements produces the same results, as it seems to me:

First:

var element = my_array.splice(0,1)[0]; 

Second:

var element = my_array.shift(); 

I want to substitute the first by the second, in my own code, to improve readability. Can I do this?

like image 438
J. Bruni Avatar asked May 24 '12 17:05

J. Bruni


People also ask

What is the alternative of splice in JavaScript?

Alternative of Array splice() method in JavaScript If the count is not passed then treat it as 1. Run a while loop till the count is greater than 0 and start removing the desired elements and push it in a new array. Return this new array after the loop ends.

What is difference between slice and splice in JavaScript?

slice returns a piece of the array but it doesn't affect the original array. splice changes the original array by removing, replacing, or adding values and returns the affected values.

Is splice destructive JavaScript?

splice() method is a destructive array method, which means it modifies the array on which it is called (disclaimer: destructive methods can be risky, especially if you use the array in question elsewhere in your program, so proceed with caution).

What is the function of splice () in JavaScript?

The splice() method changes the contents of an array by removing or replacing existing elements and/or adding new elements in place.


1 Answers

They will have the same effect, yes. splice(0, 1) will remove the first element from my_array and return a new array containing that element. shift will do the same, but return the element itself, not an array.

shift is more readable (in my opinion) and is also significantly faster (in Chrome at least):

enter image description here

like image 68
James Allardice Avatar answered Oct 14 '22 01:10

James Allardice