Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

javascript
nan
null
false
communitycreator

What are falsy values and truthy in JavaScript?

Chidume Nnamdi

JavaScript contains what are called falsy and truthy values, each of which resolves to a Booleantrue or false value. This shot focuses on falsy values in JavaScript to learn what they are and how to use them.

Falsy values

Falsy values are values that resolve to the Boolean false.

In JavaScript, we have 6 falsy values:

  1. false

  2. 0 (zero)

  3. ‘’ or “” (empty string)

  4. null

  5. undefined

  6. NaN

All these return false when they are evaluated.

  • false

If we write the following:

// bool.js
if(false) {
  console.log("yes")
}

Our code editor will indicate unreachable code. This is because the if statement evaluates the condition to true, and because the if has false, the log statement would never be displayed.

    $ node bool

Nothing is displayed. This is because false is false.

  • 0 (zero)

The number 0 is evaluated to a false.

// bool.js
if(0) {
  console.log("yes")
}else {
  console.log("no")
}

no will be printed because 0 is false, so the else part will be run.

  • ‘’ or “” (empty string)

An empty string is evaluated to be false.

// bool.js
if("") {
  console.log("yes")
} else {
  console.log("no")
}

Here, again, no will be printed.

  • null

null is evaluated to be false. null is used when we don’t want to assign a value yet to a variable. Mind you, the type of on null returns an object. So, if you want to check whether a variable initialized with null has been initialized with a value, null will return false.

// bool.js
let variable = null

if(variable) {
  console.log("yes, initialzed")
}else {
  console.log("no, not yet")
}

variable = 90

if(variable) {
  console.log("yes, initialzed")
}else {
  console.log("no, not yet")
}

The first part will log no, not yet while the second part will log yes, initialized.

  • undefined

undefined is assigned to a variable whose value has not been initialized. It resolves to false.

    // bool.js
    let undefVar

    if(unDef) {
     console.log("yes, initialzed")
    }else {
     console.log("no, not yet")
    }

    unDef = 900

    if(unDef) {
     console.log("yes, initialzed")
    } else {
     console.log("no, not yet")
    }

  • NaN

This is a number just like 0, and it resolves to false. NaN occurs when a number is divided by another data type.

// bool.js
let nanVar = 9/"str"

if(nanVar) {
  console.log("yes")
} else {
  console.log("no")
}

NaN is a falsy value, so no will be printed.

RELATED TAGS

javascript
nan
null
false
communitycreator
RELATED COURSES

View all Courses

Keep Exploring