another way to write ternary operators in javascript

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];

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

CLICK HERE to find out more related problems solutions.

Leave a Comment

Your email address will not be published.

Scroll to Top