How to Iterate Over String in JavaScript: Simple Methods Explained
You can iterate over a string in JavaScript using a
for loop, for...of loop, or string methods like split(). Each character in the string can be accessed one by one inside the loop using the string index or directly with for...of.Syntax
Here are common ways to iterate over a string:
- For loop: Use an index to access each character by position.
- For...of loop: Directly access each character in the string.
javascript
const str = "hello"; // For loop syntax for (let i = 0; i < str.length; i++) { const char = str[i]; // use char } // For...of loop syntax for (const char of str) { // use char }
Example
This example shows how to print each character of a string on a new line using both for and for...of loops.
javascript
const text = "JavaScript"; console.log('Using for loop:'); for (let i = 0; i < text.length; i++) { console.log(text[i]); } console.log('Using for...of loop:'); for (const char of text) { console.log(char); }
Output
Using for loop:
J
a
v
a
S
c
r
i
p
t
Using for...of loop:
J
a
v
a
S
c
r
i
p
t
Common Pitfalls
Some common mistakes when iterating over strings include:
- Using
for...inloop, which iterates over property names, not characters. - Modifying the string inside the loop (strings are immutable).
- Assuming string length changes during iteration.
javascript
const str = "hello"; // Wrong: for...in loops over indexes as strings, not characters for (const index in str) { console.log(str[index]); // works but not recommended } // Right: for...of loops over characters directly for (const char of str) { console.log(char); }
Output
h
e
l
l
o
h
e
l
l
o
Quick Reference
Summary tips for iterating over strings in JavaScript:
- Use
forloop with index for classic iteration. - Use
for...ofloop for cleaner, direct character access. - Avoid
for...infor strings. - Remember strings are immutable; do not try to change characters directly.
Key Takeaways
Use a for loop or for...of loop to iterate over each character in a string.
for...of loop is simpler and recommended for direct character access.
Avoid using for...in loop for strings as it iterates over indexes as strings.
Strings are immutable; do not try to modify characters inside loops.
Access characters by index with str[i] or directly with for...of.