Please read the question before marking duplicate. This isn't about an undefined variable. It's about variables which don't exist in the namespace.
I'm working on a codebase which is run in browser and in nativescript. The globals differ between the two. For instance, I'd like to check if window exists at all, but something like this:
if (!!window) {
}
will throw an error:
JS ERROR ReferenceError: Can't find variable: window
Is there a way to test whether or not a variable exists in js (not just undefined)?
globalThisstackoverflow.com/questions/57157864/… but note lack of IE supporttypeof windowand see if that's the string"undefined"typeof(window)being"undefined"and what you want here. In any valid browser environmentwindowwill not be undefined, it'll be something else. JavaScript has limited reflection capabilities and there's not really a difference between "undefined" as in declared with no value and "undefined" as in does not exist.windowwhichtypeofwill do. You could trythis['window']if your code is running in the global context. In a browser that returns something, in Node, for example, it does not.typeofis the answer. Can you explain why that's not appropriate in your use case? I can't see why not, so you'll need to fill in the gaps. This is precisely whattypeofis for: Finding out if variables exist or not. In the browser it will be defined. In a non-browser environment it probably will not, and will return"undefined".