Sometimes, we want to create an array if an array does not exist yet with JavaScript.
In this article, we’ll look at how to create an array if an array does not exist yet with JavaScript.
How to create an array if an array does not exist yet with JavaScript?
To create an array if an array does not exist yet with JavaScript, we can use the Array.isArray
method.
For instance, we write
const list = Array.isArray(x) ? x : [x];
to check if x
is an array with Array.isArray
.
If it is, then we assign x
to list
.
Otherwise, we assign an array with x
in it to list
.
Conclusion
To create an array if an array does not exist yet with JavaScript, we can use the Array.isArray
method.