1

Please check the following code:

var global_var = 1;
hello = 'hello';
global_novar = 2; 

(function () {
   global_fromfunc = 3; 
}());



var global = Object.getOwnPropertyNames(window);
    
console.log(global_var in global);
console.log(global_novar in global);
console.log(global_fromfunc in global);
console.log(hello in global);

Here only the last statement prints false on the console. However, if I assign an integer value to hello, then it prints true. Can anybody explain this behaviour?

Chava Geldzahler
  • 3,605
  • 1
  • 18
  • 32
Aniruddha
  • 3,513
  • 6
  • 27
  • 38

2 Answers2

2

Object.getOwnPropertyNames returns an array of property names. The in operator is interspecting the indexes of the array, not that its a string. Notice if I make hello big, enough, it returns false.

var global_var = 1;
hello = 270000000;
global_novar = 2; 

(function () {
   global_fromfunc = 3; 
}());



var global = Object.getOwnPropertyNames(window);
console.log(global_var in global);
console.log(global_novar in global);
console.log(global_fromfunc in global);
console.log(hello in global);

Also note that in is not the same as an array contains.

Daniel A. White
  • 187,200
  • 47
  • 362
  • 445
  • :) ok. I didnt thought of that. Maybe browser doing something for optimization. I will do more search on this.. – Aniruddha Mar 08 '17 at 00:47
2

The in operator returns true if the specified object contains the specified property. When you use it with an array, as you are doing here, the indices of the array will act as its properties.

Since global is an array, when using the in operator here, you are actually checking whether the specified index exists within this array. Therefore, a variable with an integer value returns true, so long as that index exists within global, but a variable that has a string value will return false.

To check whether a variable exists within your global array, you can use Array.prototype.includes (introduced in ECMAScript 7). This will return true for all global variables:

var global_var = 1;
hello = 'hello';
global_novar = 2; 

(function () {
   global_fromfunc = 3; 
}());



var global = Object.getOwnPropertyNames(window);

console.log(global.includes('global_var'));
console.log(global.includes('hello'));
console.log(global.includes('global_novar'));    
console.log(global.includes('global_fromfunc'));

For more on how to find a variable in an array, see this question.

Chava Geldzahler
  • 3,605
  • 1
  • 18
  • 32
  • Thanks for directing me to 'Array.prototype.includes'. Now using in, if I hello = 100, then console.log(hello in global) returns true. But, if hello = 1000, then it returns false. – Aniruddha Mar 08 '17 at 01:36
  • That's because your array `global` doesn't have 1001 items in it, so index 1000 is not present in the array, 100 is. `in` will return true if the index is present in the array, not if the variable `hello` is present. – Chava Geldzahler Mar 08 '17 at 01:38