JavaScript Truthy and Falsy

Part 2

JavaScript if (someVariable) { ... }

A common idiom is to put a variable as the condition in an if statement:

if (elementId) {

What’s going on? Well, in this context, certain values are treated as true, and others are treated as false. The term 'truthy' is often used when talking about values that are treated as true when they are in boolean context, and values treated as false are often termed 'falsy'.

Truthy and Falsy

Falsy values are:

false, null, undefined, NaN, 0, ""

All other values are truthy.

So if you have a string variable, and you want to check whether it is populated before using it, instead of

if (typeof elementId !== "undefined" && elementId !== "") {

you can just use

if (elementId) {

You just need to make sure that all the possible falsy values will give right behaviour. If, for example, zero is a valid value for elementId, then this pattern isn't appropriate.

something || somethingElse

A related idiom is:

someVariable = someVariable || "Default";

If the variable is falsy, then it is assigned the value "Default".

For example, you might use this in a function like so:

var doStuff = function (arg) {

    arg = arg || "Default";

If the code that calls the function omits the argument, arg will be undefined. In this case, the function assigns it a default value.

The reason this works is that the || operator is lazy. In its regular usage, you might have:

if (leftCondition || rightCondition) { ... }

If leftCondition is true, then rightCondition doesn’t need to be evaluated, as the OR is going to return true either way. But if leftCondition is false, rightCondition does get evaluated.

So in the statement

someVariable = someVariable || "Default";

the value "Default" will be used when someVariable is falsy (i.e. false, null, undefined, NaN, 0, "").

Knowing about truthy and falsy is essential for understanding other people's JS code, and for writing concise code.