简体   繁体   中英

Logical operators and their behavior in JavaScript

Why does this fail?

The way I read this code is "if either a or b or c equals three, then the statement is true". But apparently JavaScript disagrees. Why?

function test() {

    var a = 'one';
    var b = 'two';
    var c = 'three';

    return ( ( a || b || c ) === 'three' );

}

EDIT: am aware of the fact that i need to evaluate each expression separately, but was looking for a quicker way to write it. any suggestions will be welcome.

Your reading of the code is incorrect. Translated to a different form:

if (a) {
  return a === "three";
}
if (b) {
  return b === "three";
}
if (c) {
  return c === "three";
}

The subexpression (a || b || c) returns the first of a , b , or c that is not "falsy". That's a , because its value is "one" , so that's the overall value that's compared to "three" .

The expression ( a || b || c ) returns anything that is truthy on the first-come-first served basis. Here a is truthy and hence used. If a is falsey b will be used. If it is falsey too, c will be used.

So, you always end up comparing "one" == "three" since strings are considered truthy . You can make use of Array.some in this case, which does what you want or how you want it to behave, in your words

"if either a or b or c equals three, then the statement is true"

return [a,b,c].some(function(str){
   return str == "three";
});

This evaluates to is a, b, or c (which will be true or false) the string-equivalent of "three". Which will always be false. In order to achieve what you want, you need

return (a === 'three') || (b === 'three') || (c === 'three');

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