OneBite.Dev - Coding blog in a bite size

count a string length in Javascript

Code snippet on how to count a string length in Javascript

  var str = 'Hello World!'
  var count = 0;
  
  for (var i = 0; i < str.length; i++) {
    count++;
  }
  
  console.log(count);

This code will count the length of the string “Hello World!“. We use the variable “str” to store the string and use the variable “count” to start the count at zero. Then, we use a for loop to iterate through the string. For each character in the string, the loop will increment the count variable by 1. Finally, after looping through the entire string, we print the final value stored in the count variable to the console. The output should be 12 which is the length of the string.

javascript