-3

At what stage is the memory allocated to variables in JavaScript with respect to declaration and initialization?

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 JavaScript engine comes across a = 20 does a new memory block gets allocated to 20 to which a points?

karel
  • 4,637
  • 41
  • 42
  • 47
  • Does this answer your question? [What's the difference between using "let" and "var"?](https://stackoverflow.com/questions/762011/whats-the-difference-between-using-let-and-var) – MrCodingB Sep 11 '21 at 15:02
  • You should make a more clear distinction between variables being added to the environment plus being readable from javascript (visible effect, interesting for you), and actual memory getting allocated, that will contain actual bits (implementation detail, typically not so relevant for you). The memory for the actual bits is likely pre-allocated and pooled, much earlier than any of the code being executed. – ASDFGerte Sep 11 '21 at 15:04
  • It's an implementation detail, so as I understand it, any one implementation could handle this in different ways. – MinusFour Sep 11 '21 at 15:08

1 Answers1

0

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;
Aziza Kasenova
  • 1,315
  • 1
  • 7
  • 19
  • Your explanation is not correct, before interpretation, just in time compilator is done by JIT. This allocates memory to variables and function declarations in creation phase @Aziza Kasenova – sagg1295 Dec 30 '21 at 15:56