Insights and discoveries
from deep in the weeds
Outsharked

Thursday, April 21, 2011

Bit shift in javascript with zero for an operand

The de-facto Javascript implementation of indexOf, which many of us have used to ensure that older Microsoft browsers can parse our Javascript, is here at mozilla.org. It contains this curious little line:
var len = t.length >>> 0;

That

>>>
operator is the bit-shift operator. It causes a binary right-shift of the bits that make up it's target, by the number of bits passed in the operand. This is something you normally would only use in clever or low-level programming. I don't think I've used bit-shift operators since I was writing a device driver in C about 15 years ago.

So why would you apply a zero operand? Wouldn't that do nothing? What's this all about?

Turns out the answer is simple, and a clever tool to add to your Javascript toolbox. Basically, this ensures that len is a valid number - if t.length exists, is numeric, and is integral. If it's already good, it will be unaffected by the operation. If it's undefined or non-numeric, it will always return zero. Basically, it's shorthand for something like:

parseInt(t.length) || 0

Clever. Learn something new every day.

1 comment:

  1. Or use it to convert a decimal to an int:

    // create a random RGB color value (0-255 inclusive)
    Math.random() * 256 >> 0;

    e.g.
    0.999 * 256 = 255.744
    255.744 >> 0 = 255

    ReplyDelete