最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

angularjs - Javascript using if(foo) exists to check if variable is set - Stack Overflow

programmeradmin2浏览0评论

I realize that this question is extremely similar to many others, but I must be missing some nuance with checking whether a variable is set or not. I have seen this in other developers code:

if(foo){
  doSomething(foo);
}
else{
  alert('error of whatever');
}

With the intent that the doSomething() will only execute if foo is set or not undefined. However, when I google this, it seems everyone says "typeof" should be used instead of the above method. I specifically see this in use with angular, like this:

if($scope.property){
  dothis();
}

Am I missing something? When I see the above code, it seems to work, but all the answers I see never say this is the correct way to check if something is set or exists.

I realize that this question is extremely similar to many others, but I must be missing some nuance with checking whether a variable is set or not. I have seen this in other developers code:

if(foo){
  doSomething(foo);
}
else{
  alert('error of whatever');
}

With the intent that the doSomething() will only execute if foo is set or not undefined. However, when I google this, it seems everyone says "typeof" should be used instead of the above method. I specifically see this in use with angular, like this:

if($scope.property){
  dothis();
}

Am I missing something? When I see the above code, it seems to work, but all the answers I see never say this is the correct way to check if something is set or exists.

Share Improve this question asked Jan 29, 2016 at 18:00 hamncheezhamncheez 73912 silver badges23 bronze badges 1
  • You're likely to get subjective answers because your question in and of itself is subjective. Anytime I read something like "...seems everyone says..." I usually consider the information to follow valid and potentially a best practice, but not the end all, be all and certainly not invalidating other methods for acplishing the same goal. My point is that you should be mindful of the answers because you may not receive a concrete answer that you might otherwise be expecting. – War10ck Commented Jan 29, 2016 at 18:47
Add a ment  | 

6 Answers 6

Reset to default 5

For if() checks, in MOST scenarios where you are checking for the existence of a property on an object (your situation), what you have described is perfectly valid, easy and convenient. It checks for the existence of the property and returns true if it exists.

However, there are plenty of nuanced areas where a typeof check is "more" correct, particularly if your type is being coerced in any way via == or if you want to differentiate between null and undefined.

For instance, if null is a valid value for your property to have but undefined is not, in your example dothis() would still be called. You would prevent this with a typeof check.

if (typeof $scope.property === 'undefined') {
    dothis();
}

Finally, if you are checking for the existence of a variable instead of the existence of a property, an exception will be thrown if the variable you are checking is not defined, forcing you to use a typeof check.

In those scenarios, verbosity is your friend.

This has to do with the concept of "truthiness". Any value besides false, 0, "", null, undefined, and NaN is "truthy" which means the first block of the if-statement will run. For instance:

if ("") {
    alert("falsie"); // won't run because the empty string ("") is falsie
} else {
   alert("truthie"); // will run
}

whereas

if ("something") {
    alert("truthy"); // will run because "something" is truthy
} else {
    alert("falsie"); // won't run
}

Going back to your example, if foo is truthy (meaning that it has ANY value other than false, 0, "", null, undefined, and NaN) then it will run the first block of the if-statement (which has the doSomething() function in it).

You could also use short circuit evaluation and do this in one line.

($scope.property && doThis())

It is better to use typeof if you need to explicitly check whether the value is undefined or not. If you just want to check if the value is truthy, then you don't need typeof.

The reason the typeof operator is preferred is because it doesn't throw a ReferenceError exception when used with an undeclared variable.

However, it is important to note that variables initialized as null will return "object", so to avoid this issue, the following code is remended:

if (typeof variable === 'undefined' || variable === null) {
    // variable is undefined or null
}

What you are checking this way is if foo is not:

false
Undefined
Null
+0, −0, or NaN
Empty String

More info here:

https://javascriptweblog.wordpress./2011/02/07/truth-equality-and-javascript/

This way your function is only executed if foo is valid.

You may want to be more specific and check against a certain type with typeof.

var foo = 'foo';
if (typeof foo === 'string') { // true
  doSomething();
}

The typeof operator returns a string indicating the type of the unevaluated operand. https://developer.mozilla/en-US/docs/Web/JavaScript/Reference/Operators/typeof

发布评论

评论列表(0)

  1. 暂无评论