It means that undefined is a falsy value, list of falsy values are:
"" // Empty string
null // null
undefined // undefined, which you get when doing: var a;
false // Boolean false
0 // Number 0
NaN // Not A Number eg: "a" * 2
If you negate a falsy value you will get true:
!"" === true
!null === true
!undefined === true
!0 === true
!NaN === true
And when you nagate a truthy value you will get false:
!"hello" === false
!1 === false
But undefined is not equal false:
undefined === false // false
undefined == false // false
And just for the fun if it:
undefined == null // true
Answer from Andreas Louv on Stack OverflowIt means that undefined is a falsy value, list of falsy values are:
"" // Empty string
null // null
undefined // undefined, which you get when doing: var a;
false // Boolean false
0 // Number 0
NaN // Not A Number eg: "a" * 2
If you negate a falsy value you will get true:
!"" === true
!null === true
!undefined === true
!0 === true
!NaN === true
And when you nagate a truthy value you will get false:
!"hello" === false
!1 === false
But undefined is not equal false:
undefined === false // false
undefined == false // false
And just for the fun if it:
undefined == null // true
In javascript strict mode, undefined is not false, but javascript try to convert the object or var to a boolean value (this is called in javascript truthy value), that's the reason you got an undefined as false. This happens with null also, for example.
You can force that with this strict no equality:
if(undefined!==false) console.log("Is not false");
Videos
Falsey values in JavaScript
false- Zero of
Numbertype:0and also-0,0.0, and hex form0x0(thanks RBT) - Zero of
BigInttype:0nand0x0n(new in 2020, thanks GetMeARemoteJob) "",''and``- strings of length 0nullundefinedNaNdocument.all(in HTML browsers only)- This is a weird one.
document.allis a falsey object, withtypeofasundefined. It was a Microsoft-proprietory function in IE before IE11, and was added to the HTML spec as a "willful violation of the JavaScript specification" so that sites written for IE wouldn't break on trying to access, for example,document.all.something; it's falsy becauseif (document.all)used to be a popular way to detect IE, before conditional comments. See Why is document.all falsy? for details
- This is a weird one.
"Falsey" simply means that JavaScript's internal ToBoolean function returns false. ToBoolean underlies !value, value ? ... : ...; and if (value). Here's its official specification (2020 working draft) (the only changes since the very first ECMAscript specification in 1997 are the addition of ES6's Symbols, which are always truthy, and BigInt, mentioned above:
Argument type Result Undefined Return false.Null Return false.Boolean Return argument. Number If argument is +0,-0, orNaN, returnfalse; otherwise returntrue.String If argument is the empty String(its length is zero), returnfalse; otherwise returntrue.BigInt If argument is 0n, returnfalse; otherwise returntrue.Symbol Return true.Object Return true.
Comparisons with == (loose equality)
It's worth talking about falsy values' loose comparisons with ==, which uses ToNumber() and can cause some confusion due to the underlying differences. They effectively form three groups:
false, 0, -0, "", ''all match each other with==- e.g.
false == "",'' == 0and therefore4/2 - 2 == 'some string'.slice(11);
- e.g.
null, undefinedmatch with==- e.g.
null == undefinedbutundefined != false - It's also worth mentioning that while
typeof nullreturns'object',nullis not an object, this is a longstanding bug/quirk that was not fixed in order to maintain compatibility. It's not a true object, and objects are truthy (except for that "wilful violation"document.allwhen Javascript is implemented in HTML)
- e.g.
NaNdoesn't match anything, with==or===, not even itself- e.g.
NaN != NaN,NaN !== NaN,NaN != false,NaN != null
- e.g.
With "strict equality" (===), there are no such groupings. Only false === false.
This is one of the reasons why many developers and many style guides (e.g. standardjs) prefer === and almost never use ==.
Truthy values that actually == false
"Truthy" simply means that JavaScript's internal ToBoolean function returns true. A quirk of Javascript to be aware of (and another good reason to prefer === over ==): it is possible for a value to be truthy (ToBoolean returns true), but also == false.
You might think if (value && value == false) alert('Huh?') is a logical impossibility that couldn't happen, but it will, for:
"0"and'0'- they're non-empty strings, which are truthy, but Javascript's==matches numbers with equivalent strings (e.g.42 == "42"). Since0 == false, if"0" == 0,"0" == false.new Number(0)andnew Boolean(false)- they're objects, which are truthy, but==sees their values, which== false.0 .toExponential();- an object with a numerical value equivalent to0- Any similar constructions that give you a false-equaling value wrapped in a type that is truthy
[],[[]]and[0](thanks cloudfeet for the JavaScript Equality Table link)
Some more truthy values
These are just a few values that some people might expect to be falsey, but are actually truthy.
-1and all non-zero negative numbers' '," ","false",'null'... all non-empty strings, including strings that are just whitespaceAnything from
typeof, which always returns a non-empty string, for example:typeof null(returns a string'object'due to a longstanding bug/quirk)typeof undefined(returns a string'undefined')
Any object (except that "wilful violation"
document.allin browsers). Remember thatnullisn't really an object, despitetypeofsuggesting otherwise. Examples:{}[]function(){}or() => {}(any function, including empty functions)Errorand any instance ofError- Any regular expression
- Anything created with
new(includingnew Number(0)andnew Boolean(false))
Any Symbol
true, 1, "1" and [1] return true when compared to each other with ==.
Don't forget about the non-empty string "false" which evaluates to true
In programming, truthiness or falsiness is that quality of those boolean expressions which don't resolve to an actual boolean value, but which nevertheless get interpreted as a boolean result.
In the case of C, any expression that evaluates to zero is interpreted to be false. In Javascript, the expression value in
if(value) {
}
will evaluate to true if value is not:
null
undefined
NaN
empty string ("")
0
false
See Also
Is there a standard function to check for null, undefined, or blank variables in JavaScript?
The set of "truthy" and "falsey" values in JavaScript comes from the ToBoolean abstract operation defined in the ECMAScript spec, which is used when coercing a value to a boolean:
+--------------------------------------------------------------------------+
| Argument Type | Result |
|---------------+----------------------------------------------------------|
| Undefined | false |
|---------------+----------------------------------------------------------|
| Null | false |
|---------------+----------------------------------------------------------|
| Boolean | The result equals the input argument (no conversion). |
|---------------+----------------------------------------------------------|
| Number | The result is false if the argument is +0, −0, or NaN; |
| | otherwise the result is true. |
|---------------+----------------------------------------------------------|
| String | The result is false if the argument is the empty String |
| | (its length is zero); otherwise the result is true. |
|---------------+----------------------------------------------------------|
| Object | true |
+--------------------------------------------------------------------------+
From this table, we can see that null and undefined are both coerced to false in a boolean context. However, your fields.length === 0 does not map generally onto a false value. If fields.length is a string, then it will be treated as false (because a zero-length string is false), but if it is an object (including an array) it will coerce to true.
If fields should be a string, then !fields is a sufficient predicate. If fields is an array, your best check might be:
if (!fields || fields.length === 0)
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 ifs 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:
- 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).
- ,
eg: [ ] == false gives true, but ![ ] gives false
To solve your problem:
You can use not operator(!):
var n = null;
if(!n){ //if n is undefined, null or false
console.log('null');
} else{
console.log('has value');
}
// logs null
To answer your question:
It is considered falsy or truthy for Boolean. So if you use like this:
var n = Boolean(null);
if(n===false){
console.log('null');
} else{
console.log('has value');
}
//you'll be logged null
You can check for falsy values using
var n = null;
if (!n) {
console.log('null');
} else {
console.log('has value');
}
Demo: Fiddle
Or check for truthiness like
var n = null;
if (n) { //true if n is truthy
console.log('has value');
} else {
console.log('null');
}
Demo: Fiddle