Cast to array

JavaScript, Type, Array · Sep 15, 2020

Casts the provided value as an array if it's not one.

  • Use Array.isArray() to determine if val is an array and return it as-is or encapsulated in an array accordingly.
const castArray = val => (Array.isArray(val) ? val : [val]);
castArray('foo'); // ['foo']
castArray([1]); // [1]

More like this

  • Collection is empty

    JavaScript, Type

    Checks if the a value is an empty object/collection, has no enumerable properties or is any type that is not considered a collection.

  • Value is array-like

    JavaScript, Type

    Checks if the provided argument is array-like (i.e. is iterable).

  • Checks if the provided value is of the specified type.