4

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

3
  • for loop construction should be: for (var i=0;i<=str.length;i++)
    – Nile
    May 25, 2013 at 20:45
  • 1
    @Nile: Actually i<str.length so that you don't loop outside the string.
    – Guffa
    May 25, 2013 at 20:49
  • 3
    Doing a loop through each char in the string will be highly inefficient I recommend you do the following str.split(' ').length
    – elmuchacho
    May 26, 2013 at 15:01

4 Answers 4

5

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++) {
1
  • perfect, that was it. Thanks for getting me unstuck in my Journey to learn JS
    – Val Okafor
    May 25, 2013 at 21:09
4

I think you want to write this

for (var i = 0; i <= str.length; i++)

instead of this

for (int 0 = 1; i <= str.length; i++)

So the problems are there is nothing like int in javascript and also you are using 0=1 that doesn't make any sense. Just use variable i with var keyword.

2

This

for (int 0 = 1; i <= str.length; i++)

should be

for (var i = 1; i <= str.length; i++)

There is no keyword int in javascript

2

This is what you wanted:

function countWords(str) {
var count = 0,
i,
foo = str.length;

for (i = 0; i <= foo;i++;) {
if (str.charAt(i) == " ") {
count ++;
}

}
return console.log(count + 1);  
}


countWords("I am a short sentence");

btw. try to avoid declaring variables inside loop, it's faster when outside

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.