JSLint is not passing this as a valid code:
/* global someVar: false */ if (typeof someVar === "undefined") { var someVar = "hi!"; }
What is the correct way?
To check if a global variable exists in Python, use the in operator against the output of globals() function, which has a dictionary of a current global variables table. The “in operator” returns a boolean value. If a variable exists, it returns True otherwise False.
Use the typeof operator to check if a variable is defined or initialized, e.g. if (typeof a !== 'undefined') {} . If the the typeof operator doesn't return a string of "undefined" , then the variable is defined.
Variables that are created outside of a function (as in all of the examples above) are known as global variables. Global variables can be used by everyone, both inside of functions and outside.
To check the existence of a local variable: if 'myVar' in locals(): # myVar exists. To check the existence of a global variable: if 'myVar' in globals(): # myVar exists.
/*global window */ if (window.someVar === undefined) { window.someVar = 123456; } if (!window.hasOwnProperty('someVar')) { window.someVar = 123456; }
/** * @param {string} nameOfVariable */ function globalExists(nameOfVariable) { return nameOfVariable in window }
It doesn't matter whether you created a global variable with var foo or window.foo — variables created with var in global context are written into window.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With