lundi 3 août 2020

Why is JavaScript indexOf() not working? Why is it returning an error?

I am trying to find if a question begins with what, why, or who, and if so, set a variable focusQ to true. However, the indexOf(); function isn't working properly. It is giving me an error in the console. I have been doing a lot of Googling and I can't find the answer. What is wrong? Here is my code:

var step4 = prompt("Enter a question.");
var focusQ;
if (step4.indexOf("what") == 0) {
  focusQ = true
} else if (step4.indexOf("why") == 0) {
  focusQ = true;
} else if (step4.indexOf("who") == 0) {
  focusQ = true;
} else {
  focusQ = false;
}

console.log(focusQ)

The error it throws is:

Uncaught TypeError: Cannot read property 'indexOf' of null

What is going on here? Anyone have any working code snippets?

Aucun commentaire:

Enregistrer un commentaire