10

On a couple of polyfill examples in MDN for some Array prototype functions, there are the following two lines (e.g.: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/find):

var list = Object(this);
var length = list.length >>> 0;

I presume the first example is autoboxing(?). But what is its purpose either way if this is always going to be an array anyway?

And line 2, how does this differ to:

var length = list.length || 0;

Thanks!

keldar
  • 6,152
  • 10
  • 52
  • 82

1 Answers1

6

This makes it possible to call the function (using call or apply) in strict mode on something which isn't an array while following the specification.

If it's an instance of Array, or an array-like object, it changes nothing.

But here, as this line ensuring list is an object follows a check that this is neither null or undefined, and as other values wouldn't make the following accesses fail (apart very special cases that Object(this) wouldn't solve, like failing accessors), I'm not sure there's really a point. Maybe it was set before the check, or maybe it's here just in case of special native objects. Another possibility is that it (too?) strictly follows the specification step by step and wants to apply toObject.

list.length >>> 0 is better than || 0 in the fact it rounds to the nearest lower positive integer (in a 32 bits range). I'm not sure why >> wasn't used here, as it doesn't seem to be better to iterate until 4294967295 rather than to -1 (i.e. don't lose time).

Denys Séguret
  • 372,613
  • 87
  • 782
  • 758
  • Thanks! Any idea on the bit shifting vs OR? – keldar May 26 '15 at 10:15
  • `>>>` is better, because result is always *finite* *non-negative* *integer*, while `||` will happyly return string or object – Alexey Ten May 26 '15 at 10:26
  • When you say 'possible to call the function' which function do you mean? – AmmarCSE May 26 '15 at 10:28
  • @AmmarCSE, Denys means that the polyfilled function `find` can be called over an object which is not an `Array`. For example, read this popular answer for calling Array's function `join` over object `arguments` which is not an Array (and doesn't have all functions in prototype), although supports `length` and indexing http://stackoverflow.com/a/2091159/4573999 – Kirill Slatin May 26 '15 at 10:46
  • @DenysSequret I still find the reason for calling `Object()` function rather weak. I only see the difference in case `this` inside polyfill is `null` or `undefined`. For all other cases `Object(this)` doesn't change the nature of `this`, given the result will be only used for getting `length` property and indexing – Kirill Slatin May 26 '15 at 10:49
  • @KirillSlatin You're totally right. I'm still thinking about it. The only reasons I see for now is that the `if` check wasn't present at first. – Denys Séguret May 26 '15 at 10:49