0

Can someone explain why the boolean ("a" in window) throws true in 1st example and false in 2nd example?

I have actually no clue what is this in and how is this boolean getting calculated?

1st Example:

if ("a" in window) {
  var a = 1;
}
console.log(a);

2nd Example:

console.log("a" in window);
yunzen
  • 32,854
  • 11
  • 73
  • 106
Deadpool
  • 7,811
  • 9
  • 44
  • 88

2 Answers2

1

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 booleans, 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
Tushar Walzade
  • 3,737
  • 4
  • 33
  • 56
0

The first one returns true because the variable(a) declared gets hoisted and the if condition returns true. If the variable name is changed you will get undefined as the if condition will now return false

Refer

if ("a" in window) { 
var t = 1;
}
console.log(t);
ellipsis
  • 12,049
  • 2
  • 17
  • 33