Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does the AND (&&) operator return an array instead of a boolean?

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?

like image 810
Notbad Avatar asked Apr 08 '18 23:04

Notbad


People also ask

How do I change my keyboard keys back to normal?

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.

Why is there a symbol for and?

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.


1 Answers

The example you posted makes use of a few features of the JavaScript language:

  • "Falsy"-ness: https://developer.mozilla.org/en-US/docs/Glossary/Falsy
  • The short-circuiting nature of the && and || operators: https://en.wikipedia.org/wiki/Short-circuit_evaluation
  • The && 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 );

Explanation:

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.

like image 198
Dai Avatar answered Nov 14 '22 23:11

Dai