OneBite.Dev - Coding blog in a bite size

loop through each character in a string in Javascript

Code snippet on how to loop through each character in a string in Javascript

let string = "My String";

for (let i = 0; i < string.length; i++) {
  console.log(string.charAt(i));
}

This code simply iterates through each character in the string “My String”, beginning with the first character at index 0. Firstly, the string is assigned to the variable “string”, declared with the keyword “let”. The for loop starts by setting a variable “i” to 0. It then executes the loop as long as the value of “i” is less than the length of the string, as strings in Javascript are indexed from 0. In the loop, the character at each index is logged to the console by using the “charAt” method. Lastly, the loop increments the value of “i” by one each time, so that it can go through each character in the string.

javascript