Reputation: 20254
Can anyone explain why the >>>
bitshift operator is required in the Array.find() polyfill shown on the MDN website:
....
var list = Object(this);
var length = list.length >>> 0;
....
I understand it is sometimes used as an ugly way to truncate floating point values to integers, but that doesn't seem to be the case here, since the length
value of list
would be an integer anyway.
Upvotes: 3
Views: 109
Reputation: 288550
I understand it is sometimes used as an ugly way to truncate floating point values to integers
Not exactly. value >>> 0
is the only exposed way to use the ToUint32(value) abstract operation.
Arrays have the invariant that their length must be a Uint32 value:
Every Array object has a length property whose value is always a nonnegative integer less than 232.
That's why the spec uses ToUint32 all over the place in array method definitions. Polyfills use >>> 0
instead of ToUint32 because ToUint32 is not exposed to JS code.
You need to use ToUint32 because you can't know what this
will be in an array method, it can be a non-array object or even a primitive. Otherwise Object(this)
wouldn't be necessary neither.
Upvotes: 3
Reputation: 26191
You can apply
the Array.prototype.find()
method to any object with properties of integers >= 0 and with a length
property. Then it might be safe to truncate it's length
property first into an integer in case the length
property of our exotic array is a calculated property and not a perfect integer. Since Math.trunc()
is an ES6 functionality it fits to the nature of a Polyfill to use the >>>
operator with a 0
argument.
var obj = {7:"g", 1:"b", 2:"c", 0: "a", length: 4.7},
val = [].find.call(obj, v => v === "c");
console.log(val);
Upvotes: 1