Skip to content
Close up of a back-lit laptop keyboard

JavaScript Idioms: Part 1

Part one in a discussion on JavaScript idioms.

In this article we’ll be look at some fundamental Javascript “idioms”.

What is an Idiom?

An idiom is a pattern, often repeated and well understood by a community of programmers. By using idioms we can communicate our intent clearly, avoid pitfalls, and gain a better understanding of the big ideas behind a language. In this article we focus code patterns.

We’ll avoid formatting, naming, and other items you can find in a style guide.

Below there are a number of code examples using ES2016 syntax. The values of variables are shown in comments that look like this:

// -> true

Comparison

Use ===  or !== .

==  can be confusing, use ===  to avoid headaches.

If you want to look at the bullet you’re dodging, see here.

Gotcha
JS compares objects and arrays by reference, not by their values
This results in some surprising behaviour:

// Two empty arrays are not equal
[] === []
// Two empty objects are also not equal
{} === {}

There is one case where  ==  and  !=  are used. Instead of writing:

const partyLocation = undefined
if (partyLocation !== undefined && partyLocation !== null)

We can write:

if (partyLocation != undefined)

This will check for both null, and undefined.

When writing your own code that might not return an object, prefer returning undefined over null.

Convert a Number, String, Object Reference to a Boolean

const numberOfPeopleAttendingParty = 0
const isAnyoneAttendingTheParty = !!numberOfPeopleAttendingParty // -> false

Because of implicit type conversions in JS we can negate (!) a value to convert to a boolean, then negate that again to see if the original value coerces to true or false.

Implicit Checking

Javascript programs often take advantage of implicit type conversions to shorten tests, eg:

const numberOfPeopleAttendingParty = 0
if (!numberOfPeopleAttending)
// Instead of
if (numberOfPeopleAttending < 0)

This can sometimes cause issues, eg:

  • If 0 is a valid number of attendees
  • If you’re checking for an empty array or object, !![]  and !!{}  both return true

To check if an array is empty, check people.length .

To check if an object is empty, check Object.keys({}).length .

In your own code you can use explicit checks (eg: a.length >= 0 ). Either way, it’s still useful to be clear on what a value may return when coerced.

Summary

false , Empty String ( ""),   0  , null , undefined , and NaN all are all false in if statements, everything else, eg: -1 , "0" , "false" , [] , {}  are interpreted as true.

Check if an Object Reference Is Defined

const firstPartyGuest = undefined

// You could write
if (firstPartyGuest !== null &&
firstPartyGuest !== undefined &&
firstPartyGuest.name !== null &&
firstPartyGuest.name !== undefined)

// Or using the idiom from earlier
if (firstPartyGuest != undefined &&
firstPartyGuest.name != undefined)

// But idiomatically you'd usually type
if (firstPartyGuest && firstPartyGuest.name)

Setting a Default When We Are Unsure

const firstPartyGuest = undefined
const luckyWinner = firstPartyGuest || 'me' // -> 'me'

When we are unsure if a variable storing an object is defined, we use the or operator ( || ) to specify a default, this works because !!undefined === false.

This checks the value of firstPartyGuest , if there isn’t one, then I am the lucky winner!

Further Reading and Next Steps

While many style guides contain some idioms (eg: here and here), I recommend using a linter plug-in / auto-formatter in your favourite editor for style issues instead and focus on the code itself (eg: here)

To cement these concepts in your mind I recommend codewars.

It gives you small exercises and then a ranked list of other user’s answers.

Happy coding!

 

Banner image: Photo by Sam Albury on Unsplash 

Media Suite
is now
MadeCurious.

All things change, and we change with them. But we're still here to help you build the right thing.

If you came looking for Media Suite, you've found us, we are now MadeCurious.

Media Suite MadeCurious.