Array.of() Method
Array.of()
is kind of like Array.from()
's cousin. The difference between the two is that where Array.from()
takes any iterable and produces an array (as well as allowing some sort of data manipulation along the way), the Array.of()
method simply produces an array of all arguments passed to it.
const twelve = Array.of(12);console.log(twelve);// expected output: [12];
const items = Array.of(1, 2, 3, 4, "five", 6);console.log(items);// expected output: [1, 2, 3, 4, "five", 6]
It's also important to distinguish Array.from()
from Array()
. Consider what the following does:
const arrayTwelve = Array(12);console.log(arrayTwelve);// expected output: [ , , , , , , , , , , , ]
Cool, so it seems that Array(12)
creates an array of 12 empty slots (important: not undefined
).
But what happens when we do something like the following?
const arraySequence = Array(1, 2, 3, 4, "five", 6);console.log(arraySequence);// expected output: [1, 2, 3, 4, "five", 6]
Hmm, well that seems to do the same thing as Array.of()
. Weird. At the end of the day, I'm not really sure how or why I would use Array.of(), but it's nice to know that it's an option that behaves a bit more consistently than Array()
.
See more examples and documentation here.