Javascript !undefined gives true?
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, that's right. undefined
is a falsy value.
https://developer.mozilla.org/ru/docs/Glossary/Falsy
https://developer.mozilla.org/ru/docs/Glossary/Truthy
Yes, it is the expected behavior.
Negation of the following values gives true in javaScript:
- false
- undefined
- null
- 0 (number zero)
- ""(empty string)
eg: !undefined = true
Note: The following checks return true when you == compare it with false, but their negations will return false.
- " "(space only).
- [ ](empty array),
eg: [ ] == false gives true, but ![ ] gives false