Check for equal quantity of 2 characters in string

2735 views javascript
3

Hi I am trying to create a function in JS that takes a string and checks if there are an equal number of "x"s and "o"s in the string.

My code so far (not working):

const checkXo = (str) => {
  const y = 0;
  const z = 0;
  for (let x = 0, x < str.length, x++) {
    if (str.charAt(x) == "o") {
        y++;
    } else if (str.charAt(x) == "x") {
        z++;
    }
    }
    if (y === z) {
    return true;
  } else {
    return false;
}
}

checkXo("xxoo");

answered question

const y = 0 means you can't ever change the value of y - so this code will never work. Use let (or var) instead of const

Also, do not use for..length loops, use for (let char of string). And try an editor like VS Code that would highlight your syntax errors.

would you mind elaborating on the for (let char of string)

1 Answer

8

const defines a constant, so you won't be able to change values of y and z. Instead, you should use var or let:

let y = 0;
let z = 0;

posted this

Have an answer?

JD

Please login first before posting an answer.