Darren Wang
Darren Wang

Reputation: 47

How does Array.push() method work exactly in Javascript?

while I was taking online CS class, the topic was about an overview of how Array and memory works, and the teacher used C as an Example as that you cannot simply add extra element to an existing Array while the Array is already full with element. As a beginner developer who started with JavaScript, even though I know JavaScript is a high level language and Array.push() is already a familiar function to me, but it seems like it doesn't fit such context, out of curiosity, I've search through google and StackOverflow, I just don't see people discussing why JavaScript can just add extra elements to an existing Array.

Does JavaScript simply create a new Array with added element and point the variable I've already assigned to to the new Array or something else?

Upvotes: 4

Views: 2334

Answers (2)

Patrick Roberts
Patrick Roberts

Reputation: 51826

A JavaScript Array is not like a C array, it's more like a C++ std::vector. It grows in length by dynamically allocating memory when needed.

As stated in the reference documentation for std::vector:

Vectors usually occupy more space than static arrays, because more memory is allocated to handle future growth. This way a vector does not need to reallocate each time an element is inserted, but only when the additional memory is exhausted. [...] Reallocations are usually costly operations in terms of performance.

Upvotes: 2

Karl-Johan Sjögren
Karl-Johan Sjögren

Reputation: 17522

Arrays in javascript are not the same as an array in C. In C you'll allocate a new array with type and a fixed size and if you want to alter the size you'll have to create a new one. For javascript arrays on the other hand if you have a look at the description of arrays over at MDN you'll see this line.

Arrays are list-like objects whose prototype has methods to perform traversal and mutation operations. Neither the length of a JavaScript array nor the types of its elements are fixed. Since an array's length can change at any time, and data can be stored at non-contiguous locations in the array

So while it is called "array" it is more like a list which lets you resize it freely (and also store anything, because javascript).

There is also another question about the semantics of the push/pop methods here on SO that can shine some more light on those: How does the Javascript Array Push code work internally

Upvotes: 3

Related Questions