How to handle 'undefined' in JavaScript [duplicate]
You can check the fact with
if (typeof jsVar == 'undefined') {
...
}
As is often the case with JavaScript, there are multiple ways to do this:
typeof foo !== 'undefined'
window.foo !== undefined
'foo' in window
The first two should be equivalent (as long as foo
isn't shadowed by a local variable), whereas the last one will return true
if the global varible is defined, but not initialized (or explicitly set to undefined
).