简体   繁体   中英

Javascript logical operators and strings/numbers

I can't understand how logical operators works. I know how it works with boolean values, but what about strings or numbers?

2 && 7
returns 7

"dog" && "cat"
returns "cat"

I see, that if number or strings doesn't have same value then second value is returned. But why? For what I can use it in "real world"?

If the left hand side is true, then it evaluates as the right hand side.

If the left hand side is not true, then it evaluates as the left hand side.


false && true evaluates as the LHS. So is false .

false && false evaluates as the LHS. So is false .

true && false evaluates as the RHS hand side. So is false .

true && true evaluates as the RHS. So is true .

2 && 7 evaluates as the RHS. So is 7 (which is true).

0 && 7 evaluates as the LHS. So is 0 (which is false).

"cat" && "dog" evaluates as the RHS hand side. So is "dog" (which is true).


|| works in the same way, but returns the LHS if it is false.


For what I can use it in "real world"?

The main way you can use it is to work out if both values are true. Which is the point of the operator.

(It also has uses as a shorthand if test and for determining which of two values to assign somewhere).

The && operator does not return a boolean, it returns one of its operands. Because the operands are evaluated as booleans anyway. Since 2 is truthy , and 7 is truthy , returning 7 is the same as returning true , because the result is truthy . For 0 && 7 , it returns 0 , since that's falsey , which is the expected outcome.

In a boolean context this behaviour is identical to returning true or false , but it allows useful behaviours in other contexts. The most often encountered is:

foo = foo || 'bar';

If || (and && ) would return a boolean, you'd have to write this instead:

if (!foo) {
    foo = 'bar';
}

or:

foo = foo ? foo : 'bar';

How logical operators work is well explained on MDN Logical operators

For what can i use it in "real world"?

You can use the || operator for sorting an array on multiple keys.

Example:

const myArray = [{ age: 25, name: 'Patrick' },
{ age: 22, name: 'Greta' },
{ age: 22, name: 'Fien' }];
myArray.sort((a, b) => (a.age - b.age) || a.name.localeCompare(b.name));
console.log('myArray=', JSON.stringify(myArray));

The sort-method normally (not in the example above) returns 1, 0 or -1, so perhaps the following can help to make it easier to understand.

console.log( 1 || 1); // 1
console.log( 1 || 0); // 1
console.log( 1 ||-1); // 1
console.log( 0 || 1); // 1
console.log( 0 || 0); // 0
console.log( 0 ||-1); //-1
console.log(-1 || 1); //-1
console.log(-1 || 0); //-1
console.log(-1 ||-1); //-1

Also the 'Short-circuit evaluation' of the || operator is beneficial.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM