How to process each letter of text (with benchmarks)
https://jsperf.com/str-for-in-of-foreach-map-2
for
Classic and by far the one with the most performance. You should go with this one if you are planning to use it in a performance critical algorithm, or that it requires the maximum compatibility with browser versions.
for (var i = 0; i < str.length; i++) {
console.info(str[i]);
}
for...of
for...of is the new ES6 for iterator. Supported by most modern browsers. It is visually more appealing and is less prone to typing mistakes. If you are going for this one in a production application, you should be probably using a transpiler like Babel.
let result = '';
for (let letter of str) {
result += letter;
}
forEach
Functional approach. Airbnb approved. The biggest downside of doing it this way is the split()
, that creates a new array to store each individual letter of the string.
Why? This enforces our immutable rule. Dealing with pure functions
that return values is easier to reason about than side effects.
// ES6 version.
let result = '';
str.split('').forEach(letter => {
result += letter;
});
or
var result = '';
str.split('').forEach(function(letter) {
result += letter;
});
The following are the ones I dislike.
for...in
Unlike for...of, you get the letter index instead of the letter. It performs pretty badly.
var result = '';
for (var letterIndex in str) {
result += str[letterIndex];
}
map
Function approach, which is good. However, map isn't meant to be used for that. It should be used when needing to change the values inside an array, which is not the case.
// ES6 version.
var result = '';
str.split('').map(letter => {
result += letter;
});
or
let result = '';
str.split('').map(function(letter) {
result += letter;
});