Cast Any Value as an Array in JavaScript

in code


Another stupid little thing. In JavaScript you can use Array.from() or the spread syntax to create a shallow copy of an array or other iterable object, e.g.

Array.from(foo) // [foo]
[...foo] // [foo]

However you can’t perform this with simple values:

Array.from(9); // []
[...9] // Uncaught TypeError: 9 is not iterable

The good old fallback of Array.prototype.concat() will work great :

[].concat(foo) // [foo]
[].concat(9) // [9]
[].concat([9]) // [9]
[].concat({ id: 1 }) // [{ id: 1 }]
[].concat([{ id: 1 }]) // [{ id: 1 }]

Yay!



Coffee is Good

in code

factory_bot Email Factory

in code


Your email address will not be published. Required fields are marked *