DEV Community

Brandon Roberts
Brandon Roberts

Posted on

1

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.

Image of Wix Studio

2025: Your year to build apps that sell

Dive into hands-on resources and actionable strategies designed to help you build and sell apps on the Wix App Market.

Get started

Top comments (0)

Image of Bright Data

Ensure Data Quality Across Sources – Manage and normalize data effortlessly.

Maintain high-quality, consistent data across multiple sources with our efficient data management tools.

Manage Data

👋 Kindness is contagious

Discover a treasure trove of wisdom within this insightful piece, highly respected in the nurturing DEV Community enviroment. Developers, whether novice or expert, are encouraged to participate and add to our shared knowledge basin.

A simple "thank you" can illuminate someone's day. Express your appreciation in the comments section!

On DEV, sharing ideas smoothens our journey and strengthens our community ties. Learn something useful? Offering a quick thanks to the author is deeply appreciated.

Okay