Reputation: 11
I'm unsure how to word this exactly, what I would like to know is how does the OR operator function exactly within a conditional?
Here is the sample code, it just counts the B's in the string.
var countB = function(s) {
var counter = 0;
for (var c = 0; c < s.length; c++) {
if (s.charAt(c) == "B") {
counter++;
}
}
return counter;
}
console.log(countB("Butter balls are BBBbBBUttERRYY!"));
Now, When I run this it runs fine but when I change the if condition to
s.charAt(c) == "B" || "b"
It counts all of the characters.
Why is it doing this exactly, what is the correct syntax?
Upvotes: 1
Views: 54
Reputation: 904
What happen here in s.charAt(c) == "B" || "b"
is,
JavaScript engine first evaluate the s.charAt(c) == "B"
according to the operator precedence list in MDN. In that list ||
operator has precedence number 5 and ==
has precedence number 10. So operator that has a higher precedence number will be evaluated first
If s.charAt(c) == "B"
is true
JavaScript engine will evaluate true || "b"
that gives true
as result.
If s.charAt(c) == "B"
if flase
JavaScript engine will evaluate false || "b"
which gives result as "b"
So in side if condition coercion happens and if ("b")
will act like if(true)
and all the characters will be counted.
You can prevent this by using s.charAt(c) == "B" || s.charAt(c) == "b"
insted of s.charAt(c) == "B" || "b"
.
Upvotes: 0
Reputation: 136
If you are trying to count all 'b's(both upper and lower case), then
s.charAt(c) == "B" || s.charAt(c) == "b"
is the right way to do it.
s.charAt(c) == "B" || "b"
counts all characters because, '==' has higher precedence than logical operator, which means, JS reads your expression as:
(s.charAt(c) == "B") || ("b")
and inside an if "b" comes out as true, so, your statement becomes
(s.charAt(c) == "B") || true
and your whole expression turns out to be true.
Upvotes: 2
Reputation: 923
Here is an additional alternative that is a single compare operation and will return true if your char is upper or lower case:
s.charAt(c).toLowerCase() == "b"
"B".toLowerCase() == "b" //true
"b".toLowerCase() == "b" //true
Upvotes: 1
Reputation: 624
s.charAt(c) == "B" || "b"
is essentially equal to (s.charAt(c) == "B") || ("b")
Whenever the check for s.charAt(c) == "B"
fails, the "b"
value is truthy and it succeeds.
The correct syntax would be s.charAt(c) == "B" || s.charAt(c) == "b"
Upvotes: 5