What are the differences between JavaScript's Array.from() and Array.of() methods?
Rashid D
JavaScript'sArray.from() andArray.of() are two methods used to create new arrays, but they have different purposes and behaviors. Let's explore the differences between them:
1. Array.from():
-Array.from() creates a new array from an iterable or an array-like object by iterating over its elements.
- It accepts a mapping function as the second argument that allows you to modify or transform each element during the creation of the new array.
- It can also accept a third argument that sets the value ofthis within the mapping function.
- Example usage:Array.from(iterable, mapFn, thisArg)2. Array.of():
-Array.of() creates a new array with the specified elements as its elements.
- It takes any number of arguments and treats each argument as an individual element of the array.
- It is useful when you want to create an array with a specific set of elements, regardless of their data types.
- Example usage:Array.of(element1, element2, ..., elementN)
Here are some key differences between the two methods:
- Arguments:
-Array.from() requires an iterable or array-like object as the first argument.
-Array.of() accepts any number of arguments, treating each argument as an individual element.
- Mapping:
-Array.from() allows you to provide a mapping function as the second argument, which can transform or modify the elements during array creation.
-Array.of() does not provide a mapping function. It simply takes the specified elements as they are and includes them in the new array.
- Single Element Arrays:
-Array.from() can be used to create an array with a single element by passing an iterable or array-like object with only one element.
-Array.of() creates an array with multiple elements, treating each argument as an individual element. If you pass a single argument toArray.of(), it will create an array with that single element.
Examples:
In summary,Array.from() is used to create an array from an iterable or array-like object, with the option to map or transform the elements. On the other hand,Array.of() is used to create a new array with the specified elements as its content, regardless of their data types.