About Array.of()

Rick Waldron waldron.rick at gmail.com
Sun Aug 26 04:14:09 PDT 2012


Thanks for the feedback, allow me to explain the rationale for Array.of: 

One of the main goals of ES6 is to become a better language for library writers and code generators. 

For compilation targets, ES/JS can't assume that implementations will always know what its factories are expected to construct:

Imagine the following piece of code is used in a VM (think Dart->JS, LLJS->JS)

var o = (function( construct, ...rest ) {
  return new construct( rest );
})( factory [, variable arity args] );


If factory is Array and only one numeric arg is given, inline like this:

var o = (function( construct, ...rest ) {
  return new construct( rest );
})( Array, 10 );

The result of `o` will be an array with 10 empty indexes, as if it were called like:

new Array(10)

If you replace that by using Array.of(), you avoid this "gotcha"

More comments inline...


On Sunday, August 26, 2012 at 5:53 AM, Shijun He wrote:

> Hi,
> 
> I don't think Array.of() is useful, just stick on array literal seems enough:
> 
> var a = [1,2,3]
> var a1 = [3]
> 
> Why we need this:
> 
> var a = Array.of(1,2,3)
> var a1 = Array.of(3)
> 
> Is there any special benefit I missed?
> 
Explained above :)
 
> 
> 
> And there is another reason why I don't like Array.of() , myself write
> a small library which use Array.of(type) to get a "strong-typed"
> array:
> 
> var StringArray = Array.of(String)
> var a = StringArray.from(['a', 1, true]) // ['a', '1', 'true']
> a.push('string') // ['a', '1', 'true', 'string']
> a.push(100) // throws error
> 
> And Function.of() :
> 
> var sqrt = Function.of(Number).from(Math.sqrt)
> sqrt(9) // 3
> sqrt('9') // error
> sqrt(9, 'unwanted') // error
> 
> 

I'd argue that if code is extending ES built-ins with non-standard properties, it accepts the risk that one day it may be in conflict.

Rick
 
> 
> 
> --
> hax
> _______________________________________________
> es-discuss mailing list
> es-discuss at mozilla.org
> https://mail.mozilla.org/listinfo/es-discuss
> 
> 


-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.mozilla.org/pipermail/es-discuss/attachments/20120826/8d1d8441/attachment.html>


More information about the es-discuss mailing list