In this post we will explore all the ways we can iterate through a given “string” in JavaScript.
Different ways to iterate a JS string
const name = "Dexter";
// standard for loop
// "index", 0, "D"
for (let i = 0; i < name.length; i++) {
console.log("index", i, name[i]);
}
// "for..of", "D"
for (const char of name) {
console.log("for..of", char);
}
// "for…in", "0", "D"
// ⚠️: may pick up inherited properties.
for (const index in name) {
console.log("for…in", index, name[index]);
}
// Convert to array using spread operator
// "index", 0, "D"
// ⚠️: avoid for large strings due to memory overhead.
[…name].forEach((char, i) => {
console.log("index", i, char);
});
// Convert to array using split("") each character
// "index", 0, "D"
name.split("").forEach((char, i) => {
console.log("index", i, char);
});
// Convert to array using Array.from
// "index", 0, "D"
Array.from(name).forEach((char, i) => {
console.log("index", i, char);
});Code language: JavaScript (javascript)