15

Possible Duplicate:
What good does zero-fill bit-shifting by 0 do? (a >>> 0)

I've been trying out some functional programming concepts in a project of mine and I was reading about Array.prototype.map, which is new in ES5 and looks like this:

Array.prototype.map = function(fun) {
    "use strict";
    if (this === void 0 || this === null) {
        throw new TypeError();
    }
    var t = Object(this);
    var len = t.length >>> 0;
    if (typeof fun !== "function") {
        throw new TypeError();
    }
    var res = new Array(len);
    var thisp = arguments[1];
    for (var i = 0; i < len; i++) {
        if (i in t) {
            res[i] = fun.call(thisp, t[i], i, t);
        }
    }
    return res;
};

What I'm wondering is why it's doing t.length >>> 0. Because it doesn't seem to do anything. x >>> 0 //-> x! (as long as x is a number, obviously)

Also, note that I don't know how bitwise operators work.

Community
  • 1
  • 1
xj9
  • 3,381
  • 2
  • 24
  • 23
  • and lots of others http://stackoverflow.com/questions/1822350/ http://stackoverflow.com/questions/1474815/ http://stackoverflow.com/questions/1385491/ http://stackoverflow.com/questions/3348438/ These are easy to find only when the first one can be found >_>. – kennytm Nov 02 '10 at 19:16
  • 1
    @KennyTM ~ Good duplicates if you know what the names of the things are ... ;) – jcolebrand Nov 02 '10 at 19:31

1 Answers1

25

x >>> 0 performs a logical (unsigned) right-shift of 0 bits, which is equivalent to a no-op. However, before the right shift, it must convert the x to an unsigned 32-bit integer. Therefore, the overall effect of x >>> 0 is convert x into a 32-bit unsigned integer.

This ensures len is a nonnegative number.

js> 9 >>> 0
9
js> "9" >>> 0
9
js> "95hi" >>> 0
0
js> 3.6 >>> 0
3
js> true >>> 0
1
js> (-4) >>> 0
4294967292
kennytm
  • 510,854
  • 105
  • 1,084
  • 1,005
  • 1
    Can you please explain why something.length would be less than 0? – Patriks Jan 28 '15 at 11:05
  • @Pratik And why would it be `true`? There's probably no real-world reason for it. But if it happened (by accident eg.), it would break the `.map`. Example code: `Array.prototype.map.call({length:-2},f)` – m93a Apr 26 '15 at 09:21
  • Why would someone use Number(pos) >>> 0? Wouldn't pos >>> 0 be all you need? – 1.21 gigawatts May 12 '18 at 01:38