Check for equal quantity of 2 characters in string

2735 views javascript

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") {
    } else if (str.charAt(x) == "x") {
    if (y === z) {
    return true;
  } else {
    return false;


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


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?


Please login first before posting an answer.