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'))
CertainPerformance
374k55 gold badges354 silver badges359 bronze badges
1 Answer 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;
}
answered Aug 19, 2018 at 21:22
jh314
27.9k16 gold badges66 silver badges83 bronze badges
Sign up to request clarification or add additional context in comments.
3 Comments
Chinonso Chukwuogor
This solves the problem. but i'm still curious to know why the original code snippet returns
undefined. I would expect it to return 1jh314
word.charAt[i] is always undefined, so the if is never true.Chinonso Chukwuogor
Oh. I didn't notice charAt was being used as an array. my bad
lang-js
word.charAtis 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 aconsole.logword.charAt(i)