Search code examples
javascriptarraysecmascript-6

Weird usage of Array.of() and Array.from()?


There are two new methods of Array in ES6, Array.of() and Array.from(). The difference usage of them are mentioned in this page.

However, I am confused with the usage of Array.of in this line

// usage of Array.of
console.log(
    Array.of( "things", "that", "aren't", "currently", "an", "array" )
); // ["things", "that", "aren't", "currently", "an", "array"]

What if we do it as below,

console.log(
    [ "things", "that", "aren't", "currently", "an", "array" ]
); // ["things", "that", "aren't", "currently", "an", "array"]

The same result we can get as console.log(Array.of(...)). Any advantage of using Array.of here?

Also confused with the usage of Array.from in this line

var divs = document.querySelectorAll("div");
console.log(
    Array.from( divs )
);

What if there is no Array.from in the above codes.

var arr = [1, 2, 3];
console.log(Array.from(arr)); // [1, 2, 3]
console.log(arr); // [1, 2, 3]

Any advantage of using Array.from here?


Solution

  • Array.of()

    Brendan eich said (Source):

    Dmitry A. Soshnikov wrote:

    Brendan Eich wrote:

    So the goal of Array.of is to provide a constructor that, unlike Array, does not have that insane special case for Array(42), which presets length (and hints to implementations to preallocate) but leaves holes in [0, length).

    I still don't see how it will help in manual enumeration of the same items which may be directly passed to brackets of array initialiser. We enumerate (by hands) items here, right? -- Array.of(1, 2, 3). And we enumerate items here (by hands also) -- [1, 2, 3]. The difference is that the second case syntactically more elegant and sugared and also doesn't require non-needed function activation with allocating call-stack frame, etc.

    That's all true, but beside the point. The use-case is when you can't write a literal, because you are passing a function-that-constructs as a funarg, and the eventual caller may pass only one number arg, or several args. In that case, Array will not do the right thing in the one-number-arg case.

    That's the reason for Array.of.

    Example:

    // Array.of(42) creates an array with a single element, 42, whereas Array(42) creates an array with 42 elements, each of which is undefined.
    console.log(new Array(42));
    console.log(Array.of(42));

    Array.from()

    The Array.from() method creates a new Array instance from an array-like or iterable object.

    1. array-like objects (objects with a length property and indexed elements)
    2. iterable objects (objects where you can get its elements, such as Map and Set).

    For example:

    var m = new Map([[1, 2], [2, 4], [4, 8]]);
    console.log("m is:");
    console.log(m);
    
    var _from = Array.from(m);
    console.log("After .from: ");
    console.log(_from);