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

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.

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.

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

1 Like

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

1 Like

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