Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you implement a guard clause in JavaScript?

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

like image 492
luebken Avatar asked Mar 17 '11 12:03

luebken


People also ask

What is guard clause in Javascript?

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.

Are guard clauses good?

The use of guard clauses is a good practice to avoid unnecessary branching, and thus make your code more lean and readable.

What is a guard clause in Ruby?

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.

What is guard clause in C#?

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.


Video Answer


2 Answers

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

like image 142
Travis Webb Avatar answered Oct 20 '22 00:10

Travis Webb


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

like image 9
Shadow Wizard Hates Omicron Avatar answered Oct 19 '22 23:10

Shadow Wizard Hates Omicron