I am writing a nodejs (v4.2.4) app were I encountered some odd behaviour.
function A(number) {
this.number = number;
}
for(var i = 0; i < 3; i++) {
const a = new A(i);
console.log(a.number);
}
const b = new A(99);
console.log(b.number);
My intuition, coming from Java (and the one of FireFox), is that the output should have been
0
1
2
99
However, Node (and Chrome) give me
0
0
0
99
I investigated and understood from MSN - block scope that var
does not have block scope in javascript. Looking further, MSN - const describes a const declaration as having block scope though:
Constants are block-scoped, much like variables defined using the let statement. The value of a constant cannot change through re-assignment, and it can't be redeclared.
In that case I would say that Node and Chrome (in that case probably V8), have some kind of shady handling of const
in block scopes. But they also write that
This declaration creates a constant that can be either global or local to the function in which it is declared.
Does that mean that V8 puts every const
declaration as a global variable while FireFox creates a local one? How can it be that something crucial like that is implemented so differently?