Kiarra J.
Kiarra J.

Reputation: 51

I keep getting the error: TypeError: Cannot read property 'length' of null in Javascript

I have looked at the other threads. I am a longtime lurker, this is the first time I'm posting (I think) or it's been a while. Anyways, I know what the problem is, I think, based on the other responses, it would seem that my variable isn't initialized. But I don't think this is my issue.

I am trying to create a "Guess the word" game, similar to hangman without the stick figure. I am creating a function that sees how many times the letter is in the word. I'm not sure if I'm doing it right. Please look at my code and tell me what I'm doing wrong...?

Thank you!

function timesInWord(word, letter) {
  var re = new RegExp(letter,"gi");
  var isMatch = word.match(re).length;

if (isMatch != null && isMatch > 0) {
 return isMatch;
 } else {
 return "No Match, Try again!";
 }
}

console.log(timesInWord("Mississippi","r"));

Upvotes: 0

Views: 327

Answers (2)

Mamun
Mamun

Reputation: 68933

When there is no match found word.match(re) returns null. Trying to call length on null causes the error.

You do not need to use length property. In your case only the null checking is enough. Try the following:

function timesInWord(word, letter) {
  var re = new RegExp(letter,"gi");
  var isMatch = word.match(re);
  if (isMatch != null) {
   return isMatch.length;
   } else {
   return "No Match, Try again!";
  }
}

console.log(timesInWord("Mississippi","p"));

Upvotes: 1

Federkun
Federkun

Reputation: 36924

word.match(re) will return null if there are no matches. That's the cause of the problem. If you want to check if there are matches, before getting the length of the array, check if it's not null.

Upvotes: 2

Related Questions