Search code examples
javascriptarraysconditional-operator

Another Way to Write Ternary Operator in JavaScript


Is this logical operation:

const user = users && users[0] || null;

the same as this conditional / ternary operation:

const user = users ? users[0] : null;

? Assuming users is an array.


Solution

  • No, they are not the same. If users[0] is falsey, the || null will be selected in the first code:

    const users = [0];
    const user1 = users && users[0] || null;
    const user2 = users ? users[0] : null;
    
    console.log(user1, user2);

    The conditional operator is probably the better choice. But, even better, in modern JavaScript, you can use optional chaining instead, which is even more concise:

    let users;
    
    const user = users?.[0];
    console.log(user);

    (though, note that it gives you undefined if the nested property doesn't exist, not null)