Categories
JavaScript Answers

How to create an array if an array does not exist yet with JavaScript?

Spread the love

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.

Leave a Reply

Your email address will not be published.

If you like the content of this blog, subscribe to my email list to get exclusive articles not available to anyone else.