ilyes kooli
ilyes kooli

Reputation: 12043

Very strange behaviour comparing undefined and false

I have this output in the console:

console.log((!undefined)==(!false)) // true (fine)
console.log((!!undefined)==(!!false)) // true (still fine)

As I know, !!x==x, isn't it?

console.log((undefined)==(false)) // false

Can anyone tell me why this returns false?

Is not true that !!false==false and !!undefined==undefined?

Upvotes: 4

Views: 255

Answers (3)

user1417475
user1417475

Reputation: 236

Yes. !!x does not return x. !undefined coerces undefined to a boolean, false, then finds !((bool)undefined)=!false, if we use C++ cast notation. So !!undefined gives !!((bool)undefined)=!!(false)=!true=false, rather than undefined.

Upvotes: 6

dbkaplun
dbkaplun

Reputation: 3637

console.log(!undefined)
// true
console.log(!false)
// true
console.log(!!undefined)
// false
console.log(!!false)
// false

Upvotes: 0

sachleen
sachleen

Reputation: 31131

Undefined is not a boolean type, like false so when you compare them directly, they are not equal.

See here for other comparison pitfalls.

typeof(undefined)
"undefined"

typeof(false)
"boolean"

Upvotes: 0

Related Questions