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?
Strings (and usually numbers) are not of fixed size, and are not stored in their entirety on the stack, but within the language they behave as if they could be stored on the stack.
It's up to the one implementing the language to decide how to store the data internally. Often the data is stored in different ways depending on the value.
Although numbers in JavaScript always behave as double precision floating point numbers, usually numbers are stored differently when they happen to be integer values. Some JavaScript engines uses unused double values as integer values, some others store integers in the value itself and double values on the heap.
For strings some of the data can be stored in an item on the stack, for example the length and a reference to the string content stored on the heap. For short strings the characters could fit in the value in the stack in place of the reference, and thus need no extra data on the heap.