I came across the new Array.of() method that\'s been finalized in ES6, and I was wondering when one might use:
var a = Array.of(\'foo\', \'bar\');
I googled it for you, and the first result had a great example:
Array.of(...items)
If you want to turn several values into an array, you should always use an array literal, especially since the array constructor doesn’t work properly if there is a single value that is a number (more information on this quirk):
new Array(3, 11, 8) // => [ 3, 11, 8 ] new Array(3) // => [ , , ,] new Array(3.1) // => RangeError: Invalid array lengthBut how are you supposed to turn values into an instance of a sub-constructor of Array then? This is where
Array.of()helps (remember that sub-constructors of Array inherit all of Array’s methods, includingof()).class MyArray extends Array { ... } console.log(MyArray.of(3, 11, 8) instanceof MyArray); // true console.log(MyArray.of(3).length === 1); // true
It's also worth noting that Array.of() also preserves Array's API compatibility with TypedArray. With TypedArray (Int32Array, UInt32Array, etc.), of() is very useful. From MDN:
Uint8Array.of(1); // Uint8Array [ 1 ] Int8Array.of("1", "2", "3"); // Int8Array [ 1, 2, 3 ] Float32Array.of(1, 2, 3); // Float32Array [ 1, 2, 3 ] Int16Array.of(undefined); // IntArray [ 0 ]