How can I test a bunch of variables to see if they are defined?

javascript

#1

https://repl.it/CX8w/0

I'm really trying to show which variables in some code (a couple of quizzes) are local and which are global. I can use typeof to test each one, but can I do this DRY?


#2

How's this?

{
    let varNames = ['varNames', 'multiplier', 'input']
    for (let i = 0; i < varNames.length; i++) {
        let varName = varNames[i];
        let isGlobal = this.hasOwnProperty(varName);
        console.log(varName + " is " + (isGlobal ? "" : "not ") + "in global scope");
    }
}

The outermost braces are for avoiding creating new names in global, and let is for creating the variables in that scope (var is only local to functions, not to innermost {}


#3

:thumbsup: Thanks @ionatan -- I learned something new today.


#4

typeof would of course still work fine in a loop, maybe it's preferable since this could have been assigned to which would break my code.

..But then it would be checking the current scope, not just global..

I suppose JS is just breakable no matter what