I am new to JS and came across the term called memory heap and that variables are kept in the memory heap. But later I read that primitive values are kept in stack and reference types are kept in heap. The question is Is stack+heap=memory heap? Thank you
Asked
Active
Viewed 53 times
0
-
2Primitive values are not kept in the stack. Primitive values are kept wherever they're needed. If you have an array of primitive values, they're in the memory of the array. – Barmar Oct 01 '19 at 08:11
-
Local variables are kept in the stack. If the variable contains a primitive value, its memory is in the variable; if the variable contains a reference type, the variable contains the reference, and it points to memory in the heap. – Barmar Oct 01 '19 at 08:13
-
I can't find any reference to the term "memory heap" that doesn't just mean the same thing as "heap". Where did you learn that "variables are kept in the memory heap"? – Barmar Oct 01 '19 at 08:16
-
What actual problem are you having that needs to distinguish these terms? – Barmar Oct 01 '19 at 08:16
-
Possible duplicate of [How variables are allocated memory in Javascript?](https://stackoverflow.com/questions/2800463/how-variables-are-allocated-memory-in-javascript) – Liam Oct 01 '19 at 08:18
-
@Barmar, thank you for your kind comments:), so, if we declare variables inside function(which is considered local) and if variable contains primitive value then it is located in stack. Also, if variable contains object then it is located in heap RIght? – Dickens Oct 01 '19 at 08:19
-
Right, the stack contains the pointer to the data on the heap. Primitive values replace the pointer with the actual value. – Barmar Oct 01 '19 at 08:20
-
1@Liam, hey Liam, just wanted to ask, when we put, say, var num =5 inside a function and when function is called and pushed into call stack then is num variable pushed into call stack as well or put into heap:) Just a bit confused – Dickens Oct 01 '19 at 08:54
-
[This about covers it](https://stackoverflow.com/a/6604390/542251). Though the answer is also "it depends". I think most browsers use the [V8 engine](https://en.wikipedia.org/wiki/V8_(JavaScript_engine)) these days but something like IE 10 (for example) would use an older implementation and work differently . tl;dr *difference between real local variables and variables that are captured by closures...Captures variables are stored in a special heap allocated structure called Context* – Liam Oct 01 '19 at 09:31