Posted on

# What happens when you add one element into start of array?

When you create an array with 10 elements automatically these ten elements have an index, to make all options work easy and fast.

``````let array=[100,21,334,231,4454,656,767,878,789,12];
//  0  1   2   3   4    5   6   7   8   9

``````

NOTE: O is Big O notation is a mathematical notation that describes the limiting behaviour of a function.
to understand when I say O(1) or O(n) cost please read this table or for more check google for big o notations

first, think we talk about how much cost to add one more element at the end of this array.

``````array.push(132);
``````

is a change like that

``````let array=[100,21,334,231,4454,656,767,878,789,12,132];
//  0  1   2   3   4    5   6   7   8   9  10

``````

when you add an element to the array, it is only about adding one more index for this new element, so the cost of this is only about O(1).

but when we add one element at the start of the array, what happened?

``````array.unshift(221);
``````

result

``````let array=[221,100,21,334,231,4454,656,767,878,789,12];
//  0   1   2  3   4   5    6   7   8   9  10
``````

Do you see? directly in memory start re-indexing each element by index +1 for adding one index in the start

so the cost for this is O(n)
and take too much time then add elements in end.

everything is about time and memory for doing anything.