How to Turn Values Into Arrays in JavaScript

How to Turn Values Into Arrays in JavaScript

Ferenc Almasi β€’ 2021 July 23 β€’ Read time 1 min read
  • twitter
  • facebook
JavaScript

You can easily turn any value into an array in JavaScript by wrapping it into an Array.of array method call:

Copied to clipboard!
Array.of(7); // Returns [7]
Array.of(true, false); // Returns [true, false]
Array.of('Abbot', 'Costello'); // Returns ['Abbot', 'Costello']

No matter how many arguments you want to work with, Array.of accepts a variable number of arguments, meaning you can play with any number of values. You can also simply use the Array object as a wrapper, but note that it won't work for single numbers:

Copied to clipboard! Playground
Array.of(7); // Returns [7]
Array(7); // Returns [empty x 7]

Array(true); // Returns [true]
Array('Abbot') // Returns ['Abbot']

Have a long string that you also want to turn into numbers before turning it into an array? You can use the split method in combination with a map:

Copied to clipboard!
'123456789'.split('').map(item => Number(item)) // Returns [1, 2, 3, 4, 5, 6, 7, 8, 9]
How to Turn Values Into Arrays in JavaScript?
If you would like to see more webtips, follow @flowforfrank

50 JavaScript Interview Questions

Resources:

  • twitter
  • facebook
JavaScript
Did you find this page helpful?
πŸ“š More Webtips
Frontend Course Dashboard
Master the Art of Frontend
  • check Access 100+ interactive lessons
  • check Unlimited access to hundreds of tutorials
  • check Prepare for technical interviews
Become a Pro

Courses

Recommended

This site uses cookies We use cookies to understand visitors and create a better experience for you. By clicking on "Accept", you accept its use. To find out more, please see our privacy policy.