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'}

5. Remove Array’s Duplicates

To remove the duplicates in an array, you may create new Set (which accepts only unique keys) and parse it back to Array.

let foo = [1,2,2,3,3,3,4,4,4]
let bar = new Set(foo)
foo = [...bar] // => [1, 2, 3, 4]

6. Default Parameters

By passing the parameters in object literal notation, you get the benefit of simulating Named Parameters (A feature in programming languages that’s not supported in JavaScript).

let logUser = ({ 
        name = 'Unkown', 
        email = 'default@email.com'
    } = {}) => {
        console.log(name, email)
    }

logUser({name: 'Paul'}) // => Paul default@email.com
logUser({name: 'Paul', email: 'paul@email.com'}) // => Paul paul@email.com
logUser() // => Unkown default@email.com

The empty curly braces {} in this line } = {}) => { acts as a fallback if the function gets called without arguments.


7. Null Propagation

How many times have you encountered this error?

Uncaught TypeError: Cannot read property 'foo' of undefined

It occurs when you try to access a property of undefined variable. As in const name = response.data.user.id if the respons.data was undefined.

With the Null Propagation ?., just put a question mark ? before accessing the property.

    const username = response?.data?.user?.username

It will break the chain of accessing on the first undefined / null variable and return undefined without raising an exception.