Is it possible to reduce this conditional expression?

4

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

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

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

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

Is there any way to reduce this expression?

Note: The value of zero is not part of the possible ids .

    
asked by anonymous 02.12.2014 / 21:50

1 answer

8

Yes ,

To reduce this expression we must take into account that JavaScript evaluates a conditional expression 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

Counter intuitively someone from other languages could assume that the possible results would be only true or false .

Conclusion

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

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

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

[1] A value that is not actually false, but according to the specification behaves as if it were. See: link

    
02.12.2014 / 21:50