How are primitive data types stored in JavaScript, and how does the stack work with them? Flashcards
(3 cards)
How are primitive data types stored in JavaScript, and how does the stack work with them?
Primitive Data Types (like number, string, boolean, etc.) are stored on the stack.
The stack is a simple data structure that stores data in a LIFO (Last In, First Out) order, meaning the most recently added data is retrieved first.
Each time you declare a primitive variable, its value is stored on the stack with the variable’s name as the reference.
If you declare multiple variables with the same value, they each get separate memory locations on the stack.
Example:
let numOne = 50;
let numTwo = 50;
Both numOne and numTwo are stored on the stack at different memory locations, even though they hold the same value (50)
If you update the value of numOne to 100, will numTwo also change?
No, numTwo will not change because numOne and numTwo are stored in separate memory locations (stack). Updating one doesn’t affect the other.
Key Differences Between Primitive and Reference Data Types:
Primitive Types (e.g., String, Number, Boolean, Null, Undefined, Symbol):
Store actual values.
Are immutable (cannot be changed).
Are copied by value.
Reference Types (e.g., Array, Object, Function, etc.):
Store references (or pointers) to objects in memory.
Are mutable (can change their contents).
Are copied by reference (modifying one reference affects all references to the same object).