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

ibrahemahmad

Ibrahem ahmad

Posted on October 10, 2022

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

Enter fullscreen mode Exit fullscreen mode

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

Big O notation

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

array.push(132);
Enter fullscreen mode Exit fullscreen mode

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

Enter fullscreen mode Exit fullscreen mode

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);
Enter fullscreen mode Exit fullscreen mode

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  
Enter fullscreen mode Exit fullscreen mode

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.

💖 💪 🙅 🚩
ibrahemahmad
Ibrahem ahmad

Posted on October 10, 2022

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related