As @CertainPerformance mentioned, your var
gets hoisted to top & becomes accessible globally, it's a normal behaviour in JavaScript. FYI, they have introduced a let
keyword for a block scope in ES6.
So you can observe, both the statements are returning boolean
s, but in your if
condition, you are assigning a value 1 to the variable a
, therefore it returns the same & the later one directly returns a boolean.
In short, in the first condition, you are printing a variable value, whereas in second one, you are printing the result of a condition.
If you don't want them to be hoisted in ES5, you can effectively use
IIFEs to limit the scope as follows -
if (true) {
(function() {
var a = 1;
console.log('in block, a = ' + a); // returns 1
})(); // IIFE
}
console.log(a); // inaccessible here, returns an error
Similarly in ES6 -
if (true) {
let a = 1; // let keyword
console.log('in block, a = ' + a); // returns 1
}
console.log(a); // inaccessible here, returns an error