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
andtypeof 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
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 ."
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.
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.
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.
Since the typeof
operator comes with a higher precedence then ===
:
typeof 1
which returns a "number"
. "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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With