DEV Community

Cover image for If . . .
ogrotten
ogrotten

Posted on

If . . .

There's more than one way to skin a cat.

In JS, there is more than one way to return the result of an if.

Standard

There are further permutations, but here's the tried and true, simple and basic:

if (sky == "blue") {
    setLabel(clearday)
} else {
    setLabel(weather)
}

Ternary

The ternary operator can cleanly take the place of a simple if like the one above. It is concise and immediately readable.

(sky === "blue") ? setLabel(clearday) : setLabel(weather)

  1. Expression: It must be in parenthesis, and must be a true/false result.
  2. ? and then what to do with a true or truthy result from the expression.
  3. : and then what to do with a false or falsey result from the expression.

This can also be used as a simple way to perform a quick ifExists kind of thing.

(sun) ? setLabel(daytime) : null;

If sun has a value, then do a thing. Else, do nothing.


Short Circuit

nulling a ternary is neat and all, but it can get better. if can be 'short circuited' into something smaller that does an ifExists as well as acting on it.

let clouds = ["fluffy", "thin", "feathery"];

if (clouds && clouds.map(type => console.log(type))) {}

Line 1: set an array.

Line 2 says: if array is set and array method can run then do nothing

Except we're not doing nothing here. We want the clouds.map to be the final result, but only if the clouds array has data.

For and comparisons like this to return true, both sides must be true. Well, when JS sees that there are no clouds, it short circuits and moves on to the next step.

So, when there's data in clouds, and it returns truthy, then the map can run successfully, which will also return truthy . . . and we've tricked JS into doing something, and a kind of bonus action of what is in the brackets.

In vanilla JS this is merely ok. IMO it's more clever than it is useful.

However, its most practical use lay in React, where short circuiting can be used to show an iterating component when it exists.

{clouds && clouds.map(type => {
    <Clouds type={type} />
})}

Top comments (1)

Collapse
 
moopet profile image
Ben Sinclair

Conditions in ternaries don't need to be in parentheses.