I recently came across this question and it's answer while trying to create my own UI for code golfing. It's goal is to count the number of bytes in a given UTF-8 string:
function countUtf8Bytes(s) {
var b = 0, i = 0, c
for(;c=s.charCodeAt(i++);b+=c>>11?3:c>>7?2:1);
return b
}
Now, I primarily work with C# but I'm aware that JavaScript contains additional logical operators such as strict equality (===
), but I had never seen anything use what looked like a left or right shift (<<
and >>
respectively). However, as I broke down this snippet, I couldn't help but notice the dual usage of the ternary operator (?:
):
b += c >> 11 ? 3 : c >> 7 ? 2 : 1
I assumed this should be read as a strict evaluation, similar to strict equality. However, upon searching for the operator online with relation to JavaScript, I'm finding no evidence of this. In-fact, a few posts explicitly mention that no such operator exists (here, here and here are a few here on StackOverflow).
After learning that no such operator exists in JavaScript, I attempted to break it down and test it out. This resulted in me heading over to Playcode.io with the following snippet:
var c = ''.charCodeAt(0);
console.log(c)
console.log(c >> 11)
if (c >> 11)
console.log('3')
else {
if (c >> 7)
console.log('2')
else
console.log('1')
}
Running this snippet will produce the output:
55357
27
3
So now I'm really confused. Why is 27
evaluating as true? I continued testing and swapped for
a
. Now the output is:
97
0
1
I'd understand this result, if it weren't for the fact that step two above prints 27
.
Why is this right shift being utilized as a logical evaluation, and what am I missing here?