Considering the following scenario:
We need to use some var or function schrodinger
but do not know if it is available.
So we try:
if(schrodinger){ ... }
=> ReferenceError: schrodinger is not defined
We could use..
if( typeof(schrodinger) !== "undefined"){ ... }
=> No error. Stuff does not run
BUT, we could also use..
if( window.schrodinger){ ... }
.. as (apparently) properties become undefined
instead of null
or something?
This last point I do not understand ("Why does window.schrodinger
not throw an error?")
Is there any preference of using typeof(shrodinger)..
over window.schrodinger
?
I think it has more to do with initialisation then whether the variable is 'defined' or undefined
Javascript dynamically initialises properties (unlike a lot of other languages) and sets the property to undefined when the property is called.
Consider the following:
although testVar === undefined it does not throw a referenceError as it is initialised, but testVar2 does throw an Error as it is not initialised.
if( window.schrodinger) will function if shrodinger is defined but is FALSE or 0. I use typeof these day.