Is it possible to reduce this conditional expression?

Asked

Viewed 78 times

4

In my project I constantly come across this kind of conditional expression:

if(cliente && cliente.id) {
    return cliente.id;
} else {
    return '';
}

That is to say, "if there is a client and this client has an id then return the id value, otherwise return an empty string". This expression is useful for two reasons;

1- Avoid exceptions of the type Cannot read property of undefined/null
2- Do not return the literal undefined to the interface

Is there any way to reduce this expression?

Observing: Zero is not part of the set of ids possible.

1 answer

9


Yes,

To reduce this expression we must take into account that Javascript evaluates a conditional expression by returning the last value of the expression, which in turn is evaluated as falsy [1] or not.

Example

console.log(true && 200 && 'foobar');  //foobar
console.log(true && 200 && true);      //true
console.log(false && 200 && 'foobar'); //false
console.log(0 && 200 && 'foobar');     //0

Against intuitively someone coming from other languages could assume that the possible results would be just true or false.

Completion

To reduce the expression shown we can use the logical operator or together with the concept presented above, resulting in the following code one-Liner.

return cliente && cliente.id || '';

"If there is a client and this client has an id then return the id value, otherwise return an empty string"


[1] A value that is not actually false, but according to the specification behaves as if it were. See: http://www.sitepoint.com/javascript-truthy-falsy/

  • 2

    Excellent answer, +1! I like to see detailed and explanatory answers like this one; I already learned one more thing from Javascript today, so! o/

Browser other questions tagged

You are not signed in. Login or sign up in order to post.