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.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *