Reverse a string with loops
To reverse a string, visit its characters in a chosen order and append each character to a result.
Scan forward and prepend
Section titled “Scan forward and prepend”function reverseString(str) { let reversed = '';
for (const character of str) { reversed = character + reversed; }
return reversed;}
console.log(reverseString('code')); // 'edoc'The loop visits c, o, d, e. Each new character is added to the front of the result: c, then oc, then doc, then edoc.
Scan backward and append
Section titled “Scan backward and append”function reverseString(str) { let reversed = '';
for (let index = str.length - 1; index >= 0; index--) { reversed += str[index]; }
return reversed;}This visits the last character first and appends it to the result. Both versions take O(n) time. Since strings are immutable, repeatedly building a string may involve copying; for large inputs, converting to an array and using join() is often more efficient.
Why this loop header fails
Section titled “Why this loop header fails”This is not valid JavaScript:
// for (const (character, index) of str) { }for...of gives you each iterable value, not a pair of value and index. Use str.entries() if you need both:
for (const [index, character] of [...str].entries()) { console.log(index, character);}The spread creates an array of Unicode code points, so this form handles many emoji more naturally than indexing UTF-16 code units. For ordinary interview examples with basic English letters, either loop above is enough.
Try it
Section titled “Try it”What should reverseString('') return? Both loops return an empty string because the loop body runs zero times.