When I try to alert a negation of variable having undefined
value , I get the output as true?
alert(undefined);
alert(!undefined);
The first alert gives undefined
and second alert gives true
.
Is this the expected behavior. If so then why ?Am I missing some concept/theory about undefined
in Javascript?
undefined is true because undefined implicitly converts to false , and then ! negates it. Collectively, those values (and false ) are called falsy values.
Both undefined and null are falsy by default. So == returns true. But when we use the strict equality operator (===) which checks both type and value, since undefined and null are of different types (from the typeof Operator section), the strict equality operator returns false.
null == undefined evaluates as true because they are loosely equal. null === undefined evaluates as false because they are not, in fact, equal.
A falsy value is something which evaluates to FALSE, for instance when checking a variable. There are only six falsey values in JavaScript: undefined , null , NaN , 0 , "" (empty string), and false of course.
Is this the expected behavior.
Yes.
If so then why ?Am I missing some concept/theory about undefined in Javascript?
JavaScript has the concept of implicit conversion of values (aka coercing values). When you use the negation ("NOT") operator (!
), the thing you're negating has to be a boolean, so it converts its argument to boolean if it's not boolean already. The rules for doing that are defined by the specification: Basically, if the value is undefined
, null
, ""
, 0
, 0n
, or NaN
(also document.all
on browsers¹), it coerces to false
; otherwise, it coerces to true
.
So !undefined
is true
because undefined
implicitly converts to false
, and then !
negates it.
Collectively, those values (and false
) are called falsy values. Anything else¹ is called a truthy value. This concept comes into play a lot, not just with !
, but with tests in if
s and loops and the handling of the return value of callbacks for certain built-in functions like Array.prototype.filter
, etc.
¹ document.all
on browsers is falsy, even though it's an object, and all (other) objects are truthy. If you're interested in the...interesting...history around that, check out Chapter 17 of my recent book JavaScript: The New Toys. Basically, it's to avoid sites unnecessarily using non-standard, out of date features.
Yes, it is the expected behavior.
Negation of the following values gives true in javaScript:
eg: !undefined = true
Note: The following checks return true when you == compare it with false, but their negations will return false.
eg: [ ] == false gives true, but ![ ] gives false
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