How do you implement a guard clause in JavaScript?

一曲冷凌霜 提交于 2019-12-21 09:36:18

问题


I want to guard my functions against null-ish values and only continue if there is "defined" value.

After looking around the solutions suggested to double equal to undefined: if (something == undefined). The problem with this solution is that you can declare an undefined variable.

So my current solution is to check for null if(something == null) which implicetly checks for undefined. And if I want to catch addionalty falsy values I check if(something).

See tests here: http://jsfiddle.net/AV47T/2/

Now am I missing something here?

Matthias


回答1:


The standard JS guard is:

if (!x) {
    // throw error
}

!x will catch any undefined, null, false, 0, or empty string.

If you want to check if a value is valid, then you can do this:

if (Boolean(x)) {
    // great success
}

In this piece, the block is executed if x is anything but undefined, null, false, 0, or empty string.

-tjw




回答2:


The only safe way that I know of to guard against really undefined variables (meaning having variable name that were never defined anywhere) is check the typeof:

if (typeof _someUndefinedVarName == "undefined") {
   alert("undefined");
   return;
}

Anything else (including if (!_someUndefinedVarName)) will fail.

Basic example: http://jsfiddle.net/yahavbr/Cg23P/

Remove the first block and you'll get:

_someUndefinedVarName is not defined




回答3:


Only recently discovered using '&&' as a guard operator in JS. No more If statements!

var data = {
  person: {
    age: 22,
    name: null
  }
};

var name = data.person.name && doSomethingWithName(data.person.name);



回答4:


Ternary to the rescue !

(i) => 
    i == 0 ? 1 :
    i == 1 ? 2 :
    i == 2 ? 3 :
    null


来源:https://stackoverflow.com/questions/5339121/how-do-you-implement-a-guard-clause-in-javascript

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