How to set default value in JavaScript’s Destructuring

Did you know that it's possible to set default value in Javascript object destructuring?

Table of contents

    Let see how it works in action:

    > { firstName = "John" } = {}
    {}
    > firstName
    'John'

    One thing to keep in mind is that it only works with undefined values. It won't work with null, false and 0 as these are normal values.

    > { firstName = "John" } = { firstName: null }
    { firstName: null }
    > { firstName = "John" } = { firstName: 0 }
    { firstName: 0 }
    > {firstName = "John"} = { firstName: false }
    { firstName: false }
    Download our ebook
    Sign to our Newsletter
    Szymon Soppa Web Developer
    Szymon Soppa Curiosum Founder & CEO

    Read more
    on #curiosum blog