Syntax, Parameter and Return Value
Syntax:
_.castArray(value)
Parameters:
value: The value to convert to an array.
Return Value:
(Array) - Returns the cast array.
Examples
Casting a Single Value to an Array:
JavaScript
var _ = require('lodash');
var value = 'hello';
var array = _.castArray(value);
console.log(array);

You can also try this code with Online Javascript Compiler
Run Code
Output:
['hello']
Demonstrates casting a single string value to an array.
Handling Array and Non-Array Inputs:
function processValues(values) {
_.castArray(values).forEach(value => {
console.log('Processing:', value);
});
}
processValues('singleValue'); // Processing: singleValue
processValues(['arrayValue']); // Processing: arrayValue

You can also try this code with Online Javascript Compiler
Run Code
Shows how to handle both single values and arrays uniformly.
Casting Undefined and Null Values:
JavaScript
var undefinedValue = undefined;
var nullValue = null;
var castUndefined = _.castArray(undefinedValue);
var castNull = _.castArray(nullValue);
console.log(castUndefined);
console.log(castNull);

You can also try this code with Online Javascript Compiler
Run Code
Output:
[undefined]
[null]
An example of casting undefined and null values to arrays.
Preserving Existing Arrays:
JavaScript
var existingArray = [1, 2, 3];
var newArray = _.castArray(existingArray);
console.log(newArray); // Output: [1, 2, 3]
console.log(newArray === existingArray);

You can also try this code with Online Javascript Compiler
Run Code
Output:
[1, 2, 3]
true (same reference)
Demonstrates that an existing array is returned as is, without creating a new array.
Frequently Asked Questions
Does _.castArray() modify the original value?
No, _.castArray() does not modify the original value. If the value is not an array, it returns a new array containing the value; if it is an array, it returns the array itself.
How does _.castArray() behave with complex objects?
_.castArray() will wrap complex objects in an array, just like primitive values, unless the object is already an array.
Is it safe to use _.castArray() with all types of values?
Yes, _.castArray() is safe to use with any type of value. Non-array values are simply wrapped in an array, and array values are returned as is.
Conclusion
Lodash's _.castArray() method is a straightforward and effective tool for ensuring that any input is treated as an array. It provides a consistent way to handle inputs in functions, enhancing code clarity and reducing the need for repetitive type-checking.
You can refer to our guided paths on the Coding Ninjas. You can check our course to learn more about DSA, DBMS, Competitive Programming, Python, Java, JavaScript, etc.
Also, check out some of the Guided Paths on topics such as Data Structure and Algorithms, Competitive Programming, Operating Systems, Computer Networks, DBMS, System Design, etc., as well as some Contests, Test Series, and Interview Experiences curated by top Industry Experts.