Search code examples
javascripttypeof

understanding javascript typeof


This is a very basic issue i have as i am new to javascript but i cannot move forward until i understand this little thing.

i have this function..

function stringOrNot() {
  var input = prompt('Input something here');

  if (typeof input != 'string') {
    alert("That is not a string!");

  } else {
    alert("That is a string!");
  }
}

stringOrNot();

Question
What do i need to input to get the alert "That is not a string"?
Which kind of inputs are not strings?

Whatever i input i get 'That is a string!' returned.

also this function...

function stringOrNot() {
  var input = prompt('Input something here');

  if (typeof input != 'string') {
    alert("That is not a string!");
  } else (typeof input == 'string'){
    alert("That is a string!");
  }
}

stringOrNot();

this returns a console error

"SyntaxError: Unexpected token '{'. Parse error."

Why can i not write the if and else conditionals like this?

Please could someone explain the answers to these little problems so i can move on! thank you in advance and forgive me, i am very new to coding.

:: )

Hi again.. UPDATE and another QUESTION.

The reason I had the initial question is because of 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?


Solution

  • For stringOrNot() you have a condition in your else statement. If you wanted to have a condition, use else if () {}.

    function stringOrNot() {
    
    var input = prompt('Input something here');
    
    if (typeof input != 'string') {
        alert("That is not a string!");
    
      } else if (typeof input == 'string'){
        alert("That is a string!");
      }
    }
    

    Check below for more information

    https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/if...else

    EDITED FOR QUESTION 2:

    You include the check for the prompt because the it can also return a null value (when the user clicks exit). So when the user clicks Cancel, the "This is not a valid entry!" will appear.