0

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.

1
  • If users always is an array, it is always thruthy and testing for it is pointless. Commented Oct 31, 2020 at 19:17

2 Answers 2

2

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)

Sign up to request clarification or add additional context in comments.

1 Comment

Ah interesting, I didn't know about the optional chaining. It's like a safe call in Kotlin.
-1

Using users on its own isn't a very good way to do tests. Some languages like Go only allow tests against boolean values. To that end, it would be better to test against a boolean value if possible. Something like:

const user = users.length > 0 ? users[0] : null;

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.