Programming Questions

  • Newest
  • Popular Tags
  • Ask A Question
  • AB Check JavaScript
    My approach at the AB check was to loop through the str with "i" and "j" iterators, determine if either value is "a" or "b", then determine if either difference is equal to 4. It continuously returns false. I'm new to javascript...what am I not catching?
    function ABCheck(str) { 
      for (var i = 0; i < str.length; i++){
        for (var j = 0; j < str.length; j++){
        if((str[i] === "a" && str[j] === "b") || (str[j] === "a" && str[i] === "b")) {
            if ((str[i] - str[j] === 4) || (str[j] - str[i] === 4)) {
               return true;
                }
              return false;
                }
          }
        }
    }
    
    burnsa721 asked this question on 5/10/14 | javascript
    Answers
  • +
  • 0
  • -
  • Instead of using two loops, try using one.
  • +
  • 0
  • -
  • str[i] - str[j]
    will result in NaN as those may characters. (eg: 'a' - 'b'). So, you should check either (i - j) or (j - i) instead. ** However, you can optimize this code a lot.
    Login to write an answer