Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why typeof 1===1 returns false instead of boolean [duplicate]

Tags:

javascript

From MDN website if you look at typeof operand
Def: operand is an expression representing the object or primitive
we know that 1===1 // returns true it is a primitive type boolean and
typeof true // always returns boolean

But when i run below code

console.log(typeof 1===1);

I don't understand why it returns false instead of boolean

like image 547
nivas Avatar asked Mar 16 '17 13:03

nivas


People also ask

Why does true == true return false?

Because they don't represent equally convertible types/values. The conversion used by == is much more complex than a simple toBoolean conversion used by if ('true') . So given this code true == 'true' , it finds this: "If Type(x) is Boolean , return the result of the comparison ToNumber(x) == y ."

Why == is false?

The comparison operator ==, when used with objects, checks whether two objects are the same one. Since there are two {} in the statement {} == {}, two new objects are created separately, and then they are compared. Since they are not the same object, the result is false.

What does typeof return?

In JavaScript, the typeof operator returns the data type of its operand in the form of a string. The operand can be any object, function, or variable.

Is 1 true in JavaScript?

0 and 1 are type 'number' but in a Boolean expression, 0 casts to false and 1 casts to true . Since a Boolean expression can only ever yield a Boolean, any expression that is not expressly true or false is evaluated in terms of truthy and falsy. Zero is the only number that evaluates to falsy.


1 Answers

Since the typeof operator comes with a higher precedence then ===:

  • The first operation is actually typeof 1 which returns a "number".
  • The next operation is "number" === 1, which return false, because obviously a string isn't a number.

If you want to make it work, use parentheses inside to process the comparison (1 === 1) first and then check its type.

console.log(typeof (1 === 1));

More info: MDN Operator precedence.

like image 163
kind user Avatar answered Oct 19 '22 11:10

kind user