DEV Community

Brandon Roberts
Brandon Roberts

Posted on

A better way to turn strings into arrays!

Converting a string to an array is quite a common occurrence for most developers. But I recently found a way to do this that is more concise and readable.

How most Javascript developers turn their strings into an array:

const name = "Brandon"
name.split("")
// Result: ["B", "r", "a", "n", "d", "o", "n"]

This works perfectly fine, and is actually the way I see 90%+ of developers covert their strings into an array.

The downside for me is, it's not extremely readable for people who don't know the ins and outs of the Array.split method.

The better way to turn your strings into arrays.

const name = "Brandon"
Array.from(name)
// Result: ["B", "r", "a", "n", "d", "o", "n"]

This produces the exact same result as Array.split(""), but here your code reads like a book. Array.from(your_string) is exactly what you want to do.

Performance

I did do some research on performance differences between these two ways of converting strings to an array.
I only found one non official blog saying that Array.split is considerably faster than Array.from, however I would be interested to read more tests on this before I'm convinced. If you can provide more info on this topic please leave a comment below.

Fun Fact

Another nice thing you can do is turn a Node List into an array, using Array.from.

const pTags = Array.from(document.querySelectorAll('p'));

With this, you can create a regular array instead of a Node List when using querySelectorAll.

Top comments (0)