'Javascript string stored on stack
I'm reading Professional JavaScript for Web Developers 3rd ed. and in the summary of chapter 4 one can read:
Two types of values can be stored in JavaScript variables: primitive values and reference values. Primitive values have one of the five primitive data types: Undefined, Null, Boolean, Number, and String. Primitive and reference values have the following characteristics:
- Primitive values are of a fixed size and so are stored in memory on the stack.
But I can have different strings, say:
var a = "ABC";
// or
var b = "Some very irritatingly long string..."
They clearly differ in size, so how can they be allocated on the stack?
I believe the same question can be asked about numbers...
So I am for sure missing something important here.
Can someone explain why strings/numbers are of fixed size and how they can be stored on stack?
Solution 1:[1]
Primitive values are of a fixed size and so are stored in memory on the stack.
This seems wrong on several levels.
First, as you point out, they are not of a fixed size.
Second, even if they were, that is not necessarily a reason for storing them on the "stack".
Third, I don't even know what the "stack" is. Generally, "stack" is a term used in the context of compiled languages, most often referring to a list of invocation frames containing local variables. How JS engines store information is a matter of their internal implementation. They may use stack-like constructs, or not, or use them for some things, and not other things, or use one heap, or many heaps, or stacks containing things that point into a heap. In any case, the traditional notion of "stack" does not apply to the extent that JS supports lexical closures that require maintaining variable bindings after a function completes executing.
In any case, for the JS programmer, worrying about stacks and heaps is somewhere between meaningless and distracting. It's more important to understand the behavior of various types of values.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 |
