The JavaScript Guard and Default Operators

There are two operators used in conditionals that most developers are very familiar with. Those are logical AND (&&) and logical OR (||).

These are short circuit operators, which means that they will not execute the second condition if it is not required.

if (isCondition1 && isCondition2)

If isCondition1 is false, there is no need to compute or check the value of isCondition2.

if (isCondition1 || isCondition2)

If isCondition1 is true, there is no need to compute or check the value of isCondition2.

In C#, each side of the operator is computed as a boolean value. But, in JavaScript, that is not the case. In JavaScript the type is coerced to a bool but not actually returned as a bool, which works as expected in conditionals because you’re not actually returning a value, just checking the boolean coercion..

if (objectA)

is valid in JavaScript, because if the object is not null or undefined, it will evaluate to true, but if the object is null or undefined it will be evaluated as false.

This means that you can perform evaluations such as:

if (objectA && objectA.isCondition1)

The operator short circuits if objectA is null or undefined, so the second condition is never even checked, preventing a null reference exception when checking isCondition1. Just in case you were wondering, this is a great habit to have. In C#, instead of just listing the object as the first check you would specifically have a null check.

You don’t have to save these operators for conditionals though. In C# you can use these operators outside of conditionals in order to assign a bool value to a variable. In JavaScript outside of a conditional, the type coercion is performed to see how to handle the result, but the value returned is not necessarily a boolean value. This means that these operators work differently than you might expect.

var someObject = objectA || {};

What does that statement do? It is the default operator. It means that if objectA would be coerced into false then the right side of the operator will act as a default value, in this case someObject will be an empty object. If objectA is defined, then someObject will be a reference to objectA.

var someObject = objectA && objectB;

This is the guard operator. If objectA would be coerced into false, then someObject will be equal to objectA, otherwise it will be equal to objectB. Outside of conditionals and avoiding null reference checks I get a lot less use out of this one.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s