To check if a JavaScript global variable exists, we can check whether the variable isn’t undefined or use the hasOwnProperty with window to check whether the global variable has been added.
For instance, we can write:
if (window.someVar === undefined) {
window.someVar = 123456;
}
if (!window.hasOwnProperty('someVar')) {
window.someVar = 123456;
}
to add an if statement to check whether window.someVar is undefined .
If it is, then we set the someVar global variable to 123456.
Another way to check if the someVar global variable exists is with the hasOwnProperty method.
If window.hasOwnProperty is called with 'someVar' and that returns false , then we know that it doesn’t exist.
If it doesn’t exist, then we set window.someVar to 123456.
s