var array = props && props.children.find(ele => ele && ele.length);
The thing that is messing me up is the AND (&&
). Shouldn’t the previous line of code return a boolean? I know it doesn’t because I have tried it, and it returns an array.
Could anybody explain what is happening here?
On the Language bar, click the Input language button, and then select an input language. Click the Keyboard layout button, and then select a keyboard layout.
The & (ampersand) comes from the corruption of the Latin word “et” (and). Basically people just wrote the two letters in cursive so quickly they blurred into one symbol.
The example you posted makes use of a few features of the JavaScript language:
&&
and ||
operators: https://en.wikipedia.org/wiki/Short-circuit_evaluation
&&
and ||
operators return the "calculated value" instead of a boolean
value: Why don't logical operators (&& and ||) always return a boolean result?
It's semantically equivalent to this:
var array = undefined;
if( props /* is not null or undefined or empty-string */ ) {
array = props.children.find( ele => ele && ele.length );
}
(Note the additional &&
inside the find
predicate, so in-full it becomes this):
var array = undefined;
if( props /* is not null or undefined or empty-string */ ) {
array = props.children.find( function( ele ) {
if( ele /* is not null or undefined or empty-string */ ) {
return ele.length;
}
return undefined;
} );
}
It can also be compared to the "Elvis operator" aka Safe-navigation operator from C#:
var array = props?.children.find( e => e?.length );
The &&
operator evaluates its left operand first, in this case just props
- if it is not falsy (not null, undefined or an empty string) then it evaluates the right operand (in this case, the props.children.find
function invocation). Note that an empty array is not falsy.
If props
were falsy, then the .children.find
call would not be made, preventing a runtime error.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With