The code is:
x = 10;
if (x > 1) {
var x = x + 1;
}
console.log(x);
var x;
The output of code execution is: 11
Why is it 11? , And Why is it not an error?
Description
var declarations, wherever they occur, are processed before any code is executed. This is called hoisting and is discussed further below.
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/var#description
This means it does not matter where is your "var x", when this script is processed, the declaration will be the first.
You should understand how closures actually work.
// You define 'x' variable [1] in global scope
x = 10;
if (x > 1) {
// You define another one 'x' variable inside of 'if' scope
// So here (inside of 'if') you will interact with this variable,
// not with first one ([1])
var x = x + 1;
}
// You code run out of 'if' so you're working with
// global scope again, and your 'x' is first one [1]
console.log(x); // x = 10 still
var x;