Search code examples
javascriptif-statementshorthand

How to reduce this if statement check in JavaScript


How can I reduce this if statement in JavaScript

if(obj.attributes && obj.attributes.email === '[email protected]') { ... }

Solution

  • The line by it self is clear, however if you are looking a way to write less && operator inside you can always put things outside of the comparison such as.

    var attributes = obj.attributes || {};
    if ( attributes.email === '[email protected]' ) {
    }
    

    This makes sense if you need to make multiple checks instead of a single one, however if is a single comparison it seems like the code you already have is okay as you are making sure attributes is defined before accessing an undefined property.

    On the other hand if you have support for ES 2015 you can destruct stuff like:

    const { attributes = {} } = obj;
    if ( attributes.email === '[email protected]' ) {
    }