'Javascript !undefined gives true?

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?



Solution 1:[1]

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

Solution 2:[2]

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

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1
Solution 2 Digger2000