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.