10

I've worked with jQuery over the years. However, recently, I've found myself getting deeper into the JavaScript language. Recently, I've heard about "truthy" and falsey values. However, I don't fully understand them. Currently, I have some code that looks like this:

var fields = options.fields || ['id', 'query'];

I need to identify if fields is null, undefined, or has a length of 0. I know the long way is to do:

if ((fields === null) || (fields === undefined) || (fields.length === 0)) {
 ...                    
}

My question is, is the following the same:

if (!fields)  {
 ...
}
21

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?

9

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)
2

Short Answer:

No, they are not the same.

But this:

if (!fields) { ... }

Is the same as this:

if ((fields === null) || (fields === undefined) || (fields === 0) || (fields === '') || (fields === NaN) || (fields === flase)) { ...
}

Long (and better) Answer:

Let's first talk about truthy and falsy values.

It's all about what happens when you evaluate something as a boolean. In JavaScript, this happens when you use things like if statements; logical operators like ||, !, or &&; or the Boolean() function.

The Boolean() function accepts a value and returns either true or false.

For Example:

var age = 1; // Let's evaluate age as a boolean Boolean(age); // true

Go ahead and try this in a node repl.

A boolean can only be true or false, so the return value of Boolean() must be either true or false. In this case, we passed in the value 1, and when evaluated as a boolean, 1 is true.

Important: When evaluated as a boolean, a value must be either true or false. Those are the only two options.

In JavaScript, there are only 6 falsy values. Values that will be false when evaluated as a boolean. They are: false, 0, "", null, undefined, and NaN. So if any of these values are evaluated as a boolean, they will be false:

Boolean(false) // false Boolean(0) // false Boolean("") // false Boolean(null) // false Boolean(undefined) // false Boolean(NaN) // false

This means that any other value, in JavaScript, will be true when evaluated as a boolean. So every other value in JavaScript is truthy.

Another easy way to evaluate something as a boolean is by using the ! operator. Just like the Boolean function, this evaluates a value as a boolean. But truthy values become false and falsy values become true.

!false // true !0 // true !"" / true !null // true !undefined // true !NaN // true

Again, try this out in a node repl or something to make sure you understand.

So this statement:

if (!fields) { ... }

Is saying the following: "if fields, when evaluated as a boolean, is false, then run the code inside this if statement."

As for your first statement:

var fields = options.fields || ['id', 'query'];

You are working with the logical OR operator, which is worth reading about to make sure that you understand. https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Logical_Operators

0

Your code means:

var fields;
if (options.fields)
    fields = options.fields;
else
    fields = ['id', 'query'];

Now options.fields is converted to a boolean value. By definition null, undefined, 0, "" is converted to false, (mostly) anything else is converted to true (but I don't want to be so precise).

It does not mean the same, because the fields.length === 0 line. Empty arrays and other objects are converted to true.

note: Javascript is sometimes a big mess... For example there is no real need for 2 type checking operators (typeof and instanceof). It just confuses ppl when true instanceof Boolean does not work and using typeof(true) == "boolean" is error prone because of typing a string without autocompletion. Maybe in some new versions these problems will be solved.

-1

You can try (!! fields) if the fields element is null, undefined or has a length of 0 it would return true. Or (!!! fields) then this would return true.

the double ! or !! will force true or false. I wish I can find a good definition for this but I don't seem to be able to find it again.

  • 1
    "!!!" is the same as "!" by definition, as is "!!!!!" and "!!!!!!!". "Notting" a value can be used to confirm that something is truthy or falsy, which definitely has its place, but it doesn't fully answer the OP's question. That is, what exactly are truthy or falsy values? – Jeffrey Sweeney Dec 16 '15 at 17:36
  • I found an article that better describes the not not operator: bennadel.com/blog/… developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/… It will turn your condition into a boolean value. – Randy Collier Dec 18 '15 at 2:20

Not the answer you're looking for? Browse other questions tagged or ask your own question.