user1778543 user1778543 - 2 months ago 6
Javascript Question

For loop is this returning 1 for count when >1 expected

Below is my code:

function onlyYou(s){
s = s.split("");
for (var i = 0; i < s.length; i++){
var count = 0;
if (s[i] = "r"||"a"||"w"){
count = count + 1;
};
};
alert(count);
};

onlyYou("you");


Running this code returns 1 and I'm not understanding why exactly, even if I put "y"||"o"||"u" it returns 1 instead of 3

Any help would be much appreciated

Answer

On each iteration of the for loop, the variable count is set to equal 0 and then the if statement is evaluated, so count can only ever be equal to 0 or 1, regardless of input.

You should declare count outside of the for loop like this:

function onlyYou(s){
  s = s.split("");
  var count = 0;
  for (var i = 0; i < s.length; i++){
    if (s[i] = "r"||"a"||"w"){
      count = count + 1;
    };
  };
  alert(count);
};

onlyYou("you");

Also, your condition if (s[i] = "r"||"a"||"w") is incorrect. Firstly, a single = indicates an assignment and not an evaluation, you should use == since this compares the two arguments, s[i] = "r" merely sets the variable s[i] to have the value "r". Also, || "a" is equivalent to || true since you aren't comparing "a" to anything.

The condition should be:

if (s[i] == "r" || s[i] == "a" || s[i] == "w")