Search code examples
javascriptif-statementbooleancharat

charAt not evaluating


I am trying to write a function that will evaluate equality of characters in a string and return true if 3 in a row match. The charAt() doesn't seem to be working as the if statement always goes to the else block.

function myFunction(num1) 
{
var checkNum1;
  for (var i = 0; i < num1.length; i++)
  {
    if (num1.charAt(i) == num1.charAt(i+1) && num1.charAt(i) == num1.charAt(i+2))
    {
    checkNum1 = true;
    break;
    }
  }
  if (checkNum1 == true)
  {
  return true;
  }

  else
  {
  return false;
  }
}

What should I be doing to get the last "if" block to return true?


Solution

  • The code that you have provided works fine with strings ie: myFunction("257986555213") returns true.

    However, myFunction(257986555213) returns false as expected as charAt is a String method.

    As a fail-safe approach, you can try adding the following line to your method at the beginning:

    num1 += '';
    

    This should convert your argument to string and you should get your results..

    Hope it Helps!!