Should not this function return a bool instead of a Pizza?

4

I'm studying react and I came across the following expression:

{this.state.text.split(' ').map((word) => word && '

asked by anonymous 26.09.2018 / 19:26

3 answers

5

The && operator in Javascript evaluates the first expression, and if it is something that can be considered true, it returns the value of the second expression.

For example:

console.log('a' && 'b' && 'c');

The values 0, 0.0, null , undefined , false , '' and NaN are considered false. The rest is considered true.

    
26.09.2018 / 19:46
3

This behavior is called Short-Circuit Evaluation or Short Circuit Evaluation ( Wikipedia and MDN ), which basically means: "If I already know the answer, I will not even check it out."

Take the truth tables of an AND and an OR as an example:

+---------+-------+-------+  +---------+-------+-------+
|           AND           |  |            OR           |
+---------+-------+-------+  +---------+-------+-------+
|     entrada     | saída |  |     entrada     | saída |
+---------+-------+-------+  +---------+-------+-------+
| false   | false | false |  | false   | false | false |
| false   | true  | false |  | false   | true  | true  |
| true    | false | false |  | true    | false | true  |
| true    | true  | true  |  | true    | true  | true  |
+---------+-------+-------+  +---------+-------+-------+

We can see that AND will only be true if ALL of its entries are true, and OR will only be false if ALL of its entries are false. Then the interpreter does not need to know what comes after a false && ... because it is already known that the result is false .

So when we have:

obj.attr && doSomething(obj.attr)

It will only execute the doSomething function if obj.attr is any value truthy .

As well as:

let valor = param || default;

The variable valor will receive the first value truthy that it finds from the left to the right. If you do not find any, it will be the last value (in this case default );

    
26.09.2018 / 20:34
2

The map function takes the values from the array and uses them as the input key (any typed word) and maps all to the same value (the pizza).

The end ( '

26.09.2018 / 19:47