What is array from() in Javascript?
Overview
The function from converts any iterable object to an array. The general syntax for from is:
array.from(object)
Parameters
The function from has 1 mandatory and 2 conditional parameters. The mandatory input parameter is the object that shall be converted to an array. One optional parameter is a map function to be called on all keys of the array. The other optional parameter is to be used as ‘this’ for the map function.
Return value
The function from returns an array.
Example
The following example will help you understand the function from more in depth.
The first example converts a word to an array. We do not need the optional map function parameter for this. The from function breaks each letter of the word into an array.
The second example is of an array of numbers. We want to attain an array of numbers that is one greater than each of the original array numbers. Hence, for the map function, we add 1 to each of the numbers, i.e., x=>x+1.
const arr = [1,3,5]const ret1 = Array.from('hello')const ret2 = Array.from(arr, x => x + 1)console.log(ret1)console.log(ret2)
Free Resources