My point is that a local primitive variable in a function is allocated on the stack and not in the main heap of memory (it's different if it is an object), this memory isn't "being used" it's just an offset from the current stack pointer.
The moment we "close over" a function then the function definition is converted internally into a class and the value of that variable becomes a property of the instance of that class. The stack is a super efficient way of handling primitive value storage during the execution of a function. If x was an object then it wouldn't be the same story, as the reference to x would be stored on the stack but the contents of x would be allocated in memory and be subject to subsequent garbage collection, leading to additional processing requirements. In neither of these cases would the variable be "used" as in it wouldn't continue to take up required memory after the function exited, however as Javascript uses garbage collection it would need processing for the memory to be made available again.
functionmultiply(y){letx=10**10returny*x}// This function does NOT allocate 10000000 copies// of x in memory, the same location on the stack is used each time.// No additional memory will be consumed and// there will be no garbage collectionfor(leti=0;i<10000000;i++){console.log(multiply(i))}
Consider this:
functionmultiply(y){letx={pow:10**10}returny*x.pow}// This function DOES allocate 10000000 copies of x in memory,// however NO additional memory will be permanently held// as garbage collection will free the temporary values as they are no longer// accessible.for(leti=0;i<10000000;i++){console.log(multiply(i))}
For further actions, you may consider blocking this person and/or reporting abuse
We're a place where coders share, stay up-to-date and grow their careers.
My point is that a local primitive variable in a function is allocated on the stack and not in the main heap of memory (it's different if it is an object), this memory isn't "being used" it's just an offset from the current stack pointer.
The moment we "close over" a function then the function definition is converted internally into a class and the value of that variable becomes a property of the instance of that class. The stack is a super efficient way of handling primitive value storage during the execution of a function. If
x
was an object then it wouldn't be the same story, as the reference tox
would be stored on the stack but the contents ofx
would be allocated in memory and be subject to subsequent garbage collection, leading to additional processing requirements. In neither of these cases would the variable be "used" as in it wouldn't continue to take up required memory after the function exited, however as Javascript uses garbage collection it would need processing for the memory to be made available again.Consider this: