Store strings as arrays of characters. (YDKJS Types and Grammar)

In types and grammar, the author mentioned this briefly. In order not to switch from strings to arrays every time you use them, you can store strings as arrays rather than strings.

Here’s the quote:

The other way to look at this is: if you are more commonly doing tasks on your “strings” that treat them as basically arrays of characters, perhaps it’s better to just actually store them as arrays rather than as strings. You’ll probably save yourself a lot of hassle of converting from string to array each time. You can always call join("") on the array of characters whenever you actually need the string representation.

I would like to know some of the examples, and how to implement this… I get the idea of it, but I dont know a real world example that reflected his view. Do you guys do this just to save time? Is it a better practice just to save strings as arrays of characters? If so how to do it?

Thanks in advance.

I recall that many fcc challenges required you to convert strings to arrays, or at least this was the most common way to solve them, especially the string manipulation ones. So I would say that this method is commonly used in string manipulation problems.

I also think that the method you mentioned would best be used when you need to convert the string more than once in your code, so that you don’t have to repeat the same process (the code to convert) again and again. So yea, I would say it’s a better practice in this case.

An example would be the Reverse a String challenge.

And this how to save a string as an array of characters:

var str = "hello";
var strArr = str.split('');

Implementation is easy (just call split on the string). As for use cases, I’m sure there are some, but in most general-purpose scenarios, you’ll find it’s best to store strings as strings. That way, you can call native string methods and easily use the full range of regex functionality.

If you include algorithm challenges, the number of use cases for storing strings as arrays increases massively. But that’s more coding interview territory than production code territory.

1 Like