Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

I\'ve worked with jQuery over the years. However, recently, I\'ve found myself g

ID: 647835 • Letter: I

Question

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) {
...
}
Thank you!

Explanation / Answer

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

Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
Chat Now And Get Quote