jstone jstone - 1 year ago 119
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

appear in

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) {
console.log('The letter `letter` occurs in `word` 1 time.');
return letter;

Answer Source

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) {
  return count;
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download