WTFTW — What the Fact this Week

What The Fact This Week!

Smart JavaScript with && and ||

The && (‘and’) and || (‘or’) are logical operators in Javascript with two very specific properties:

1. They short-circuit evaluations

2. They evaluate to their last evaluated operator

A little about Javascript’s truthy falsy behavior (attitude actually!) :

Falsy Values: null, false, 0, undefined, NaN, and “” (empty string).
Truthy Values: Anything other than the falsy values.
Even though Infinity is considered a special number just like NaN, it is still evaluated as truthy, and not falsy, while NaN is falsy.

Now that we are verse with basics, lets see how && (‘and’) and || (‘or’) can make our code better

Example 1. Basic setting default values

function bookName (title) {
if (!title) {
title = “Untitled Book”;
};
}

Better approach:

function bookName (title)​{
title = title || “Untitled Book”;
}

So why is this better, because its less code, cleaner, not re inventing what’s already available! The || operator first evaluates the expression to its left, if it’s truthy, it returns that value and checks no further. If it’s falsy, it evaluates and returns the value of the expression on the right.

Example 2. Smart conditional check

function canVote (age) {
if (age && age > 17) {
return true;
}
​else {
return false;
}
}

Better approach:

function canVote (age) {
return age && age > 17 ;
}

The && operator first evaluates the expression to its left, if falsy, returns false and does not evaluate the right operand. If the the first expression is truthy, it also evaluates the expression on the right and returns the result.

Example 2. Ninja level assignment

var userID;
​if (userID && userID.loggedIn) {
userName = userID.username;
}
​else {
userName = null;
}

Better approach:

var userName = userID && userID.loggedIn && userID.username;

If userId is truthy, call userId.loggedIn and check if it is truthy, if it is truthy, then get the username from userId. If userId is falsy, return null.

One clap, two clap, three clap, forty?

By clapping more or less, you can signal to us which stories really stand out.