troblom
troblom

Reputation: 1

Stuck on a variable that doesn't seem to update on a loop

this is basic rehearsal from Eloquent JavaScript.

However I only get "0" as a result. For some reason the loop doesn't update the "count" variable:

function countChar(str, n){
  let count = 0;
  for(let i = 0;i == str.length-1; i++){
    if(str[i] == n){
      count++;
    }
  }
  return count;
}

console.log(countChar("dazzled", "z"));

Upvotes: 0

Views: 63

Answers (2)

Lloyd Nicholson
Lloyd Nicholson

Reputation: 484

You haven’t specified when you want the count variable to update properly. You’ve said this

i == str.length-1

Which won’t update. It should be something like this

i<= str.length-1

Upvotes: 0

tomerpacific
tomerpacific

Reputation: 6475

The problem is in your for loop statement.

You have:

for(let i = 0;i == str.length-1; i++)

Where it should be :

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

Upvotes: 2

Related Questions