Member-only story
Use Strings as Array Efficiently in JavaScript
Resolve routine tasks in an unusual way
Have you ever tried to look at a string in JavaScript from a different angle? You know that we can convert it to an array, but it can actually behave like a real array.
Hello, world! Today I want to share with you some cool stuff that may help you in your work or at least to show off knowledge during an interview.
Routine Tasks
Our example will be pretty simple, but it will help you change your paradigm regarding this topic.
For instance, you may face a problem when you have to separate each letter in a word and maybe put it back again. Usually, we use split
to convert a string to an array and then join
to put it back to the initial state, but with the needed separator:
const str = 'Hello';
str.split('').join('-'); // 'H-e-l-l-o'
String As Array
As David Flanagan says in his book JavaScript: The Definitive Guide, a string in JavaScript imitates an array. We can prove it pretty easily. Instead of using the charAt
method, we can get the necessary letter with the usage of square brackets. Yes, it doesn’t look like a compelling argument, but at least it’s something: