Lodash _.castArray() method
What you’ll learn
- How
_.castArray(value)ensures your logic always receives an array. - Why existing arrays are returned directly instead of being wrapped again.
- How
null,undefined, objects, and strings behave with castArray. - When castArray is better than manual
[value]wrapping.
Prerequisites
Skim Lodash Lang methods first so you can compare castArray with nearby converters like toArray.
- You understand basic JavaScript values (primitive, object, array, nullish).
- You can run snippets in Node or open the Try-it labs in a browser.
Overview
_.castArray is a small normalization helper. It guarantees an array output shape so mapping, iteration, and validation code can use one consistent branch.
Single output shape
Great for APIs that accept one or many values; your downstream code always receives an array.
No double wrapping
Arrays are returned directly, so [1,2] stays [1,2] instead of [[1,2]].
Predictable nullish handling
_.castArray(null) becomes [null] and empty call returns [].
Syntax
_.castArray(value) - value: any JavaScript value (optional).
- Returns: an array. If input is already an array, the same reference is returned.
Wrap a single value
Non-array values are wrapped into a one-item array so downstream loops can stay consistent.
import castArray from "lodash/castArray";
castArray(42); // [42]
castArray("hello"); // ["hello"] Already an array
If the input is an array, castArray returns it unchanged, avoiding nested array output.
import castArray from "lodash/castArray";
const nums = [1, 2, 3];
const result = castArray(nums);
console.log(result === nums); // true Null and undefined behavior
null becomes [null], and no-argument call returns an empty array.
import castArray from "lodash/castArray";
castArray(null); // [null]
castArray(); // [] 📋 castArray vs alternatives
| Approach | Array input | Scalar input |
|---|---|---|
_.castArray(value) | Returns same array | Wraps into single-item array |
[value] | Creates nested array ([[...]]) | Wraps into single-item array |
_.toArray(value) | Converts/copies elements | May split strings or return object values |
Pitfalls to avoid
Using [value] blindly
Manual wrapping can produce nested arrays when input is already an array. Prefer castArray when shape is unknown.
Confusing castArray with toArray
castArray normalizes container shape; toArray converts/splits values into elements.
Assuming a cloned array
Existing arrays are returned by reference. Clone separately if you plan to mutate and need isolation.
❓ FAQ
Summary
- Purpose:
_.castArraystandardizes unknown input into an array shape. - Behavior: it preserves existing arrays and wraps non-arrays.
- Next: continue to Lodash _.clone().
_.castArray(value) returns value as-is when it is already an array, so no extra wrapper array is created.
6 people found this page helpful
