admin管理员组

文章数量:1323529

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

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

Share Improve this question asked Mar 11, 2015 at 21:15 bluebyblueby 812 silver badges9 bronze badges 2
  • Suggestion: what's wrong with if (!s) {...}? Also: look here: stackoverflow./questions/27509/… – paulsm4 Commented Mar 11, 2015 at 21:18
  • Because undefined can be reassigned, you should always check against the type anyway. – SeanCannon Commented Mar 11, 2015 at 21:18
Add a ment  | 

2 Answers 2

Reset to default 6

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

Use if(window.myVarible) instead. If you check for the variable per se, JavaScript will try to execute or check the value of the variable1 which in turn yields this error message.

You can also use if(typeof myVarible !== "undefined") which will only look at the type of the variable but not at its value.


1The way that JavaScript checks for the value of a variable depends on whether that variable was written as an object property like window.myVar or without.

本文标签: