Does anyone know why would this happen for below code
if(myVarible !=undefined){ myVarible.doSomething() }
myVariable is A global object that is used only on some pages I am sure I've done this in a past and it always worked. I also tried
if(!!s){}
Which I am also sure I've used in the past.
finally got it to work with if(typeof s!=="undefined"){}
but I would like to know why undefined variable is not equal to undefined
and why did it work in the past?
Thanks
From what I understood, the problem is, that on some pages you don't create the global myVarible
variable at all.
For such case checks
myVarible !== undefined
and
typeof myVarible !== "undefined"
are not equal. The difference is, that only typeof
operator can handle non-existing references to names (e.g. variables). All other language constructs throw ReferenceError
when encountering reference that cannot be resolved. typeof
returns the string "undefined"
for this case.
So, in your case, you should use the typeof
operator or check existence of the variable
property on global object.
if (window.myVarible) {}
link to ecma-script specification defining typeof behavior
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With