Browse - Programming Tips - What's the best way to check if a javaScript global variable is defined?

Date: 2019jan3
Language: javaScript
Keywords: is_defined, isDefined

Q.  What's the best way to check if a javaScript global variable is defined?

A.  If you use the variable anywhere but in typeof() you get an error.
So that means the solution is to use typeof()

if (typeof(gMyGlobal) !=== 'undefined') { console.log('is is defined'); }
Or you can make a function
function isMyGlobalDefined() { return typeof(gMyGlobal) !=== 'undefined'; }
Note we use 'undefined' unquotes and not undefined because typeof() returns a string.