Is there a nice simple way to check if a variable in Javascript has a value?

本秂侑毒 提交于 2019-12-05 20:26:00

If you know the context of myVar, you should be able to do this:

if (this.myVar != null) {
    ...
}

If you want to allow 0 and "" as valid values and you want to cover the case of the variable might not even be delcared, but don't consider null a valid value, then you have to specifically check for undefined and null like this:

if (typeof myVar !== 'undefined' && myVar !== null) 
   ...

A lot of values are falsey (they don't satisfy if (myVar) so you really have to conciously decide which ones you're testing for. All of these are falsey:

undefined
false
0
""
null
NaN

If you want to allow some, but not others, then you have to do a more specific test than if (myVar) like I've shown above to isolate just the values you care about.

Here's a good writeup on falsey values: http://www.sitepoint.com/javascript-truthy-falsy/.

If you know the variable has been declared and you just want to see if it's been initialized with something other than null, you can use this:

if (myVar != undefined) 
   ...

Using only the != instead of !== allows this to test for both undefined and null via type conversion. Although, I wouldn't recommend this because if you're trying to discern between falsey values, it's probably better to NOT let the JS engine do any type conversions at all so you can control exactly what it does without having to memorize all the type conversion equality rules. I'd stick with this to be more explicit:

if (typeof myVar !== 'undefined' && myVar !== null) 
   ...

If you want to know if it has any non-falsey value, you can of course do this (but that won't allow 0 or "" as valid values:

if (myVar) 
   ...

The 2-part method. If you don't check for the typeof first, you'll end up with a reference error.

if myvar could be undefined, calling it without the typeof check will throw an error.

And if it is defined as null (like myvar= element.lastChild for an element with no children) you will miss catching it if you just use typeof.

Well, null is a defined value... so if you want to make sure that the variable doesn't contain null, and isn't undefined you must do both checks.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!