⟵back

Default values in JavaScript

Something I've enjoyed about using JavaScript at work is observing its differences to Python (the language I learnt to code in). There are fun little one-liners for setting variables conditionally, making use of operators that aren't used in Python. Credit for the idea for this post goes to Razan Aboushi, though I've adapted and expanded the examples myself.

Basic check

This is your bog-standard check, using the exclamation mark bang operator, aka "logical not" operator. If name is falsy, name will be set to 'Default User'.

if (!name) {
    name = 'Default User'
}

Ternary operator

I must admit, when first learning JavaScript, using ternary operators for conditional rendering in React, it took a while to get my head around! I do like how it almost resembles a human expression, as if it's asking a question. "Name? Name. Else email."

username = name ? name : email

Nullish coalescing

In programming, "coalescence" means finding the first non-null value out of two or more values. This checks specifically for null or undefined values and will ignore other falsy ones, such as 0 or ''. We basically skip a step from the ternary approach.

username = name ?? email

So here, if name is defined, then username = name. If name is undefined, username = email.

Nullish coalescing with assignment

Here, both the check (for null or undefined) and assignment of the variable are carried out in one step. Example from Mozilla:

const a = { duration: 50 };
a.speed ??= 25;
console.log(a.speed);  // expected output: 25
 
a.duration ??= 10;
console.log(a.duration);  // expected output: 50

There is no such thing as a.speed; before performing the check, it is undefined. Therefore it's logical that 25 would be the output here.

In the second part, we try to access a property that does exist: a.duration. This is truthy, so we get an early return. The value of a.duration is returned.