简体   繁体   中英

Javascript variable memory allocation

At what stage is the memory allocated to variables in Javascript wrt declaration and initialisation?

console.log(a); // Prints undefined
var a;
a = 20;

For the above snippet, a = undefined even before the code execution starts. Does that imply that memory has been allocated during the creation of the variable environment with no value ( undefined )? If yes, during code execution phase, when the JS engine comes across a = 20 does a new memory block gets allocated to 20 to which a points ?

It's called hoisting.

From the MDN Web Docs documentation on hoisting :

the interpreter allocates memory for variable and function declarations prior to execution of the code

Think of it as if all your variables, declared as var in future, are first read and set to undefined . The changes on the variable value later will be assigned to the same variable.

 console.log(a); // undefined var a; a = 20; console.log(a); // 20

Note that, you are only able to do it with var -- let and const are read only at the their declaration point.

console.log(b); // ReferenceError: b is not defined


console.log(c); // ReferenceError: c is not defined
let c = 1;


console.log(d); // ReferenceError: d is not defined
const d = 1;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM