Search code examples
javascriptcoercion

Difference between !typeof str == "string" and typeof str != "string"


I was writing a simple if condition that checks the type of the input. I used !typeof str == "string" it did not work, so i used typeof str != "string" instead of it. it worked. this is the function:

function reverseStr(str) {
  if (typeof str != "string" || !str) {
      return "Please enter a valid str";
  }

  var oldList = str.split("");
  var newList = [];
  for (let i = oldList.length - 1; i >= 0; i--) {
      newList.push(oldList[i]);
  }
return newList.join("");

}

so what is the difference between them?


Solution

  • Due to operator precedence (! has a greater precedence that ==), !typeof str == "string" is equivalent to (!typeof str) == "string", which means the boolean value opposite to the type of str is equal to "string" and will always be false since !typeof str returns false, and false != "string".

    typeof str != "string" works because it means the type of str is not equal to "string".