Can someone explain why in javascript,
alert({} == true) shows false
if ({}) alert('true') shows true ?
What’s different in the if condition that changes the result?
I wanted to write some shorthand argument validator obj || (obj = {}); and I was baffled by this discovery.
if ({}) alert('true')->true{}is an object, which, when evaluated in the context of anifstatement, gets coerced to aBoolean, and sinceBoolean({})evaluates totrue, you getif (true). This is documented in the ECMAScript specification, Section 12.5 The if Statement:alert({} == true)->falseThis one is more tricky. From the ECMAScript specification, Section 11.9.3 The Abstract Equality Comparison Algorithm:
Thus,
{} == truewill be evaluated as{} == Number(true), which is evaluated to{} == 1, which isfalse.This is also why
1 == trueevaluates totrue, but2 == trueevaluates tofalse.