Stand in Line. Insert item in an array without .push()

Stand in Line. Insert item in an array without .push()
0

#1

Tell us what’s happening:

I did it okay with .push() but I was wondering how to do it without .push().

I did

 arr[arr.length + 1] = item

But when the array is empty, obviously, it becomes the index 1 not zero, so the array is [undefined, item].

I supose I’d use a simple if.

(arr.length >  0) ?  arr[arr.length] = item : arr.[0] = item

But I think it lacks of sense.

Just out of curiosity.


#2

Yes, you can do it like that. Array(...arr, item) probably works as well, not tested though. Or arr.concat(item). None of these do what push does though (append an item to the array and return the new array length), though that doesn’t matter a lot in this case.


#3

It’s worth noting that the length of an array is already larger than the max index of the array, e.g. a length 1 array has 0 as it’s max index


#4

Pay close attention to what @gebulmer said. He is giving you an important hint to fix your code.


#5

Ah I see, it’d be without +1 at the length. Okay!