Home > Blockchain >  Difference between Array.from() and normal initialization
Difference between Array.from() and normal initialization

Time:07-27

Is there any difference in initializing array using Array.from([arrayElements]) and var <variable_name>=[arrayElements].

If yes, when to use Array.from()? I suppose we use Array.from() when some kind of a transformation is needed to be applied on the array elements.. But for any transaformation we can use [Arrayelements].map(mappingFn) which I think eliminates the need of Array.from()? Correct me if I am wrong.

CodePudding user response:

One difference between using array literals const x = [elements] or const x = new Array(elements) and Array.from() is, that the Array.from method can be used to create an array from arrayLike/iterable objects (while new Array() or using array literals requires you to pass a deconstructed (spread) array)

(additionally you can pass Array.from() a map Function - which will work quite similar to the array.map method)

More clearly, Array.from(obj, mapFn, thisArg) has the same result as Array.from(obj).map(mapFn, thisArg), except that it does not create an intermediate array, and mapFn only receives two arguments (element, index) without the whole array, because the array is still under construction.

Note: This is especially important for certain array subclasses, like typed arrays, since the intermediate array would necessarily have values truncated to fit into the appropriate type.

from mdn (https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/from)

So Array.from() has its use cases (otherwise it would not have been implemented as its own method), but unless you need it I would suggest sticking to the traditional ways of creating arrays.

CodePudding user response:

While selected elements using the getElementsByClassName, all the array methods cannot be used as it isn't a proper array.

By using Array.from(document.getElementsByClassName('el')), all array methods like forEach, reduce, map are available. I mainly used this for looping through all elements with a same class name.

I suppose [arrayElements] is valid but looking at the syntax, it seems like all the elements are just put into a new array where all array methods work.

  • Related