6
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?

Sebastian Simon
  • 18,263
  • 7
  • 55
  • 75
Notbad
  • 5,936
  • 12
  • 54
  • 100
  • 1
    Possible duplicate of [Why don't logical operators (&& and ||) always return a boolean result?](https://stackoverflow.com/questions/5417969/why-dont-logical-operators-and-always-return-a-boolean-result) – Sebastian Simon Apr 08 '18 at 23:47
  • 1
    See [`logical operators`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Logical_Operators) => `short-circuit evaluation` for more info. – Arman Charan Apr 09 '18 at 01:06

3 Answers3

11

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

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.

Dai
  • 141,631
  • 28
  • 261
  • 374
2

It's a way of checking to see if props is truthy before trying to delve deeper into its properties. If you simply did

var array = props.children.find(ele => ele && ele.length);

then if props was null, the line would generate an error. But if you know that props might be null and are OK with that, you can try to generate the array anyway, then when using it later, check to see if array is truthy before using it:

var array = props && props.children.find(ele => ele && ele.length);
CertainPerformance
  • 356,069
  • 52
  • 309
  • 320
1

Basically, if props is defined the search its children for the first one that has an element with one or more nodes and assign it to array.

var array;
if (props) {
    array = props.children.find(ele => ele && ele.length);
}
Chris Camaratta
  • 2,729
  • 22
  • 35