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



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?


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 {}


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


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