Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Simple JavaScript Word Count Function

Tags:

javascript

I finally started to learn JavaScript and for some reason I can't get this simple function to work. Please tell me what I am doing wrong.

function countWords(str) {
/*Complete the function body below to count
  the number of words in str. Assume str has at
  least one word, e.g. it is not empty. Do so by
  counting the number of spaces and adding 1
  to the result*/

var count = 0;
for (int 0 = 1; i <= str.length; i++) {
   if (str.charAt(i) == " ") {
        count ++;
    }
}
return count + 1;
}
console.log(countWords("I am a short sentence"));

I am getting an error SyntaxError: missing ; after for-loop initializer

Thanks for your assistance

like image 419
Val Okafor Avatar asked Dec 12 '22 14:12

Val Okafor


1 Answers

There is no int keyword in Javascript, use var to declare a variable. Also, 0 can't be a variable, I'm sure that you mean to declare the variable i. Also, you should loop from 0 to length-1 for the characters in a string:

for (var i = 0; i < str.length; i++) {
like image 159
Guffa Avatar answered Jan 02 '23 08:01

Guffa