25

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?

J. Bruni
  • 20,322
  • 12
  • 75
  • 92

4 Answers4

57

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

James Allardice
  • 164,175
  • 21
  • 332
  • 312
  • 1
    I've upvoted everybody's answer - but chosen yours because of the extra performance graphic and information. Thanks to all! – J. Bruni May 24 '12 at 17:43
6

Both lines of code remove the first element from the array, and return the removed element, they are both supported in all major browsers.

You should use the second one, and the code will be more readable indeed.

Bergi
  • 630,263
  • 148
  • 957
  • 1,375
Maxim Krizhanovsky
  • 26,265
  • 5
  • 59
  • 89
2

shift returns the element that was removed, splice returns an array of elements that were removed.

that being said, the two statements do the same thing and i would agree that the second is more readable.

jbabey
  • 45,965
  • 12
  • 71
  • 94
-1

splice will return as an array but not remove data from the object instead make a copy


shift just give one data from front and also remove from object


For example,

const object = {1}
object.slice(); // return [{1}]
//object will be : {1}
object.shift(); // return {1}
//object will be : {} as shift remove the front data 
  • 2
    First, the code example itself is wrong. Second I think you mixed up splice and slice. Splice does indeed mutates the array i.e. it _will_ modify the original array as does shift. Slice on the other hand doesn't mutate the array and returns a new one. – Sushil Oct 07 '21 at 10:14