Does the following:
x || x === {}
not mean !!x
, that is, x
is defined?
Does the following:
x || x === {}
not mean !!x
, that is, x
is defined?
That comparison makes no sense, because either x
is truthy, then you get the result of x
, or falsy, you get false
(a falsy value is never strict equal to an empty object instance).
A concise version would be
x || false
for give me x
or false
.
x || x === {}
means basically x || false
.
!!x
means "is x
truthy", so it's not exactly the same - x || x === {}
will return x
if x
is truthy.
In the same case, !!x
will return true
.
||
operator means "if left side is truthy (not null
, not undefined
, not 0
etc. - see All falsey values in JavaScript for details) return left side, else return right side".
On the right side you have x === {}
which always evaluates to false
, since strict comparison means comparing reference-wise (i.e., "is x
the same object as {}
, which is never true)
!!x
and x || x === {}
will be the same only if x === true
or x === false
||
returns the left hand side if the LHS is a true value. So if x
is a true value, it returns x
.
Otherwise, it compares x
to a new object, which will always be false
, and returns that.
So if x
is true, you get (an unmodified) x
otherwise you get an explicit boolean false
.
This is different to !!x
since that would return a boolean true
if x
was a true value.