Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Uncaught ReferenceError: myVarible is not defined in if statement comparing to undefined

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

like image 343
blueby Avatar asked Mar 16 '23 19:03

blueby


1 Answers

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

like image 173
Rafael Avatar answered Apr 06 '23 23:04

Rafael