简体   繁体   中英

Can someone explain to me how the scope of the logical "OR" operator works in Javascript?

here's my code.

function getVowelCount(str) {
 let array = str.split("");
 let vowelCount = array.reduce((acc, curr) => {
   if (curr === 'a' || curr === 'e' || curr === 'i' || curr === 'o' || curr === 'u') {
     acc++
   } return acc
 }, 0);
 return vowelCount
}

I'm new to coding and I've started with Javascript. Could someone be so kind as to explain why I can't use "(curr === 'a' ||'e' || 'i' || 'o' || 'u')" in my if statement. I thought that would have been processed as; "If the current value is 'a' OR 'e' OR 'i' etc...

Thanks.

=== has higher order of operations than || . Operators of equal order are evaluated left to right.

(see mdn for full order).

So curr === 'a' ||'e' || 'i' || 'o' || 'u' curr === 'a' ||'e' || 'i' || 'o' || 'u' curr === 'a' ||'e' || 'i' || 'o' || 'u' is equivalent to

(((((curr === 'a') ||'e') || 'i') || 'o') || 'u')

Which can be reduced to curr === 'a' ? true : 'e' curr === 'a' ? true : 'e' .

Just like there's an order of operations for math (multiplication/division before addition/subtraction), javascript's operators have an order . In (curr === 'a' ||'e' || 'i' || 'o' || 'u') , the highest priority is the === , so it starts by comparing curr === 'a' . This is going to result in either true or false . Let's assume false .

Next up there's all the || 's. These are done left to right, so it compares false || 'e' false || 'e' . Every string except for an empty string is "truthy", so false || 'e' false || 'e' is truthy as well.

It would continue moving to the right, except logical OR operators will short circuit once the outcome is guaranteed. So the whole expression is truthy.


Even if || had a higher precedence, it wouldn't make this work. With 'a' || 'e' 'a' || 'e' , both of those are "truthy", so it just takes the first truthy value, which is a . And this would repeat, meaning 'a' || 'e' || 'i' || 'o' || 'u' 'a' || 'e' || 'i' || 'o' || 'u' 'a' || 'e' || 'i' || 'o' || 'u' is a complicated way of saying 'a' .

 console.log('a' || 'e' || 'i' || 'o' || 'u')

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