Search code examples
javascripttypeof

JavaScript typeof


I have a question about a codeschool.com function exercise which concluded as this...

function countE() {
  var phrase = prompt("Which phrase would you like to examine?");

  if (typeof(phrase) != "string") {
    alert("This is not a valid entry!");
    return false;
  } else {
    var eCount = 0;

    for (var i = 0; i < phrase.length; i++) {
      if (phrase.charAt(i) === 'e' || phrase.charAt(i) === 'E') {
        eCount++;
      }
    }
    alert(eCount);
    return true;
  }
}
countE()

So.. I wanted to test what is not a string, I wanted to get the alert "This is not a valid entry!".

But, if a prompt only returns a string then why is this << if (typeof(phrase) != "string") >> included in the function?

Sorry to ask this basic question here, codeschool discussion page did not give me an answer and I am very curious to know.

Thank you. J


Solution

  • Pressing Cancel or Esc will return null. This is the check you should be interested in.

    cancel

    preview

    Reference: MDN prompt.

    Note: You don't need to use () with typeof. So change it to:

    if (typeof phrase != "string") {
    

    Other Scenarios

    When you are expecting a number, like age or something, you can use:

    if (isNaN(phrase)) {
    

    The above might help you to decide if it is a number or not.