0

My return variable keeps coming back undefined. Can someone please explain why? as far as I can tell it should be in scope.

var countBs = function(word) {
  var count = 0;
  for (var i = 0; i < word.length; i++){
    if (word.charAt[i] == 'B'){
      count += 1;
      return count;
    };
  };
};

console.log(countBs('BBABBAB'))

4
  • 1
    word.charAt is a function. When you develop - ensure you understand every expression in your code and that you have checked that every expression returns exactly what you expect - using a debugger or at least a console.log Commented Aug 19, 2018 at 21:17
  • @Luca Explain why? Maybe he doesn't want to iterate if a value is found? Commented Aug 19, 2018 at 21:19
  • Thank you! I just figure it out. Man what a Duh moment. Commented Aug 19, 2018 at 21:20
  • word.charAt(i) Commented Aug 19, 2018 at 21:21

1 Answer 1

1

You need to return count at the end of the function, and use .charAt(i):

var countBs = function (word) {
  var count = 0;
  for (var i = 0; i < word.length; i++){
    if (word.charAt(i) == 'B'){
      count += 1;
    };
  }
  return count;
}
Sign up to request clarification or add additional context in comments.

3 Comments

This solves the problem. but i'm still curious to know why the original code snippet returns undefined. I would expect it to return 1
word.charAt[i] is always undefined, so the if is never true.
Oh. I didn't notice charAt was being used as an array. my bad

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.