What @EdmundoRodrigues says is almost correct, except that it works for var
(IT DOESN'T in this case, but it works for inexistent global property assignment... "set", independently of undefined
.
You can't detect the case of a variable (using var
declaration) being added by var
too, because the var
statement declares variables instantly (sorry if my terms doesn't fit, English isn't my primary language), e.g.:
(_ => {
a = "10"
var a
alert(self.a) // undefined on window (global object)
// So the variable a can be assigned and used before the var
// keyword comes.
// If var [a] were not declared here, a would be global, or
// if it was strict mode, an exception would have been
// thrown.
}) ()
It's like this for var
, except for let
and const
:
( _ => {
a = "10" // Uncaught ReferenceError: a is not defined(…)
let a
})()
Your function will only count global var
statement used in next-separate scripts to be executed yet, and will also count fine any global object properties that were not existent earlier in the current executing expression/statement, independently of the undefined
value.
const
and let
will be only visible in the entire scope until their declaration are executed, unlike var
. And as @EdmundoRodrigues says, let
and const
variables are visible locally only, independently of the scope (even when the scope is global).
# Checking your code (note: I made a change to detectWhatIsNew
to return all recent variables and declared myVariable
with var
).
"use strict"
const detectWhatIsNew = _ =>
Object.getOwnPropertyNames(self).filter(key =>
!notNew.includes(key) && notNew.push(key))
const notNew = Object.getOwnPropertyNames(self)
var myVariable
console.log(detectWhatIsNew()) // an empty array
This won't work for var
, but it does make sense! Because the presence of var
is instant, the Object.getOwnPropertyNames(self)
call would have captured this "a"
in any position.
console.log(notNew.indexOf( "myVariable")) // bigger than -1
But your function will still work for different ways of setting global variables, like:
self.myVariable2 = "19"
console.log(detectWhatIsNew()) // Array { "0": "myVariable2" }