0

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?

Hazel へいぜる
  • 2,751
  • 1
  • 12
  • 44
  • 3
    Any nonzero number evaluates to true, zero evaluates to false. The shift operator has nothing to do with it. – Wiktor Zychla Aug 26 '21 at 21:07
  • Javascript works similar to C/C++ where `0` is false and anything not zero is true. So `1` is true and `27` is true and `-101` is true. In addition javascript also considers other things to be true. A non-empty string is true so `"hello"` is true but `""` is false. An object is true, an array is true etc. Values considered false are `false`, `0`, `undefined`, `null`, the empty string and `NaN` (note that the empty array is true) – slebetman Aug 26 '21 at 21:45

0 Answers0