JavaScript Tips & Tricks

Continuously updated collection of the tips and tricks I use in my daily work. Some introduce complexity or reduce readability – the trade off is to use what suites you in your own context.


1. If statement alternative

In JavaScript, the conditional statement is executed from left to right. If a single condition is false, all the conditions on its right will not be executed.
So false && console.log('foo') will never print a foo.

This could be useful as a replacement for if statement.

// Instead of this...
if (foo !== undefined) {
    console.log(foo)
}

You can type..

foo && console.log(foo)

A practical example is when you try to access objects properties, if the object is undefined it will raise an excpetion.

let foo
console.log(foo.bar) //  Excpetion: `Cannot read property 'bar' of undefined`

To be in the safe side, only access the object’s property if it’s not undefined:

foo && console.log(foo.bar)

2. The not not !! operator

Any variable could be turned into a boolean form by using the precedent !!.
A null, undefined, 0 and empty string "" will evaluate to false. Otherwise, true.

Instead of strictly checking if a variable equals undefined or null… or if the string is empty foo.length == 0

if (foo === undefined || foo === null ) { ... }

if (foo.length == 0 ) { ... }

You can just type !!foo

if (!! foo) { ... }

3. Conditional spread operator

Spread operator is used to exapand an array and add more elements to it.

let foo = [1,2,3]
let bar = [4,5,6]
let fooBar = [...foo, ...bar] // return [1,2,3,4,5,6]

We can append an array based on certain conditions by surronding the conditional statement with two braces ( ). This can be useful whenever you’re forced to write inline JavaScript.

let fooBar = [...(foo.length > 10 ? foo : [] ), ...bar]

This line of code implies the following: only append foo if it has more than 10 elements.

⚠️ Caution: This may make your code less readable, I only use it when I’m forced to write inline JavaScript.


4. Return Object with Arrow Function

Arrow functions implicitly return a value if its body has only single expression, without using braces.

const foo = () => 'bar' // => bar

If braces are used, it should explicitly return a value

const foo = () => { 'bar' } // => undefined
const foo = () => { return 'bar' } // => bar

Now, if you want to return an oject implicitly (since the object literal already has braces), you can surround it with parentheses

const foo = () => { foo: 'bar' } // => undefined
const foo = () => ({ foo: 'bar' }) // => {foo: 'bar'}