jstone jstone - 5 months ago 11
Javascript Question

Count how many times a single letter appears in a word

I am very new to JavaScript, and I'm trying to figure out how to count how many times a single letter appears in a word. For example, how many times does

'p'
appear in
'apple'


Here is what I have written so far but am having trouble figuring out where am I going wrong.

var letterInWord = function (letter, word) {
var letter = 0;
var word = 0;
for (var i = 0; i < letter.charAt; i+= 1) {
if (letter.charAt(i) === " " = true) {
letter++;
console.log('The letter `letter` occurs in `word` 1 time.');
}
}
return letter;
};

Answer

You've got a number of problems:

  1. You're reusing parameter names as local variable names. Use different identifiers to track each bit of information in your function.
  2. letter.charAt is undefined, if letter is a number, and is a function if letter is a string. Either way, i < letter.charAt makes no sense.
  3. If you're searching for letter in word why do you want to look at letter.charAt(i)? You probably want word.charAt(i).
  4. " " = true makes no sense at all.

Perhaps you meant something like this?

var letterInWord = function (letter, word) {
  var count = 0;
  for (var i = 0; i < word.length; i++) {
    if (word.charAt(i) === letter) {
        count++;
    } 
  }
  return count;
};
Comments