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
What Are Guard Clauses? A guard clause is simply a single piece of conditional logic at the beginning of a function which will return from the function early if a certain condition is met.
The use of guard clauses is a good practice to avoid unnecessary branching, and thus make your code more lean and readable.
TLDR; a guard clause is a premature return (early exit) that "guards" against the rest of your code from executing if it's not necessary (based on criteria you specify). Soon after I started my career as a Ruby on Rails developer I learned about guard clauses and how they can improve code readability.
In simple language we can say that the code that validates your method's input is called a Guard clause. It makes your code more understandable and it protects you from bugs and unexpected behaviors. The if block act as a guard clause by protecting the GetStudent method against any null _student arguments.
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
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With