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?
-
In JavaScript, only objects and arrays are mutable, not primitive values. ... A mutable object is an object whose state can be modified after it is created. This means the object is the same along with the memory reference. developer.mozilla.org/en-US/docs/Glossary/MutableGary– Gary2021年02月14日 09:23:35 +00:00Commented Feb 14, 2021 at 9:23
-
developer.mozilla.org/en-US/docs/Web/JavaScript/… and stackoverflow.com/questions/12640216/…potatopeelings– potatopeelings2021年02月14日 09:24:10 +00:00Commented Feb 14, 2021 at 9:24
-
A array.push adds item to the end of the array C and a removal using pop() removes the item from the end of object C array developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/…Gary– Gary2021年02月14日 09:26:18 +00:00Commented Feb 14, 2021 at 9:26
2 Answers 2
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
Comments
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.