DEV Community

Cover image for Truthy And Falsy Value In JavaScript.
Md. Azad Ul Kabir
Md. Azad Ul Kabir

Posted on

Truthy And Falsy Value In JavaScript.

There are two most important terms to understand when you execute some code based on an "if else" statement. Truthy and Falsy value.
Truthy value: Data types that return true by default are called truthy.
False value: Data types that return false by default are called falsy

  • All values are truthy except these values
  • +0 or -0
  • BigInt zero (0n)
  • Empty String ("")
  • null, undefined, and NaN

For example below this code we are performing a Linear search. But when I apply a condition for "value not found" I have a complexity for array index 0. Because it's a falsy value if I use the findIndex variable value as an 'if' condition. I solved this in my way. But there have several ways to solve this.

Image description

Top comments (2)

Collapse
 
ant_f_dev profile image
Anthony Fung

Truthiness and Falsiness can be a difficult concept when coming from more strongly typed languages.

I quite often see things like if (array.length > 1), which is necessary for languages like C#, but can be achieved with if (array.length) in JavaScript.

Another stumbling block I sometimes have is assuming values that should be boolean are boolean because they are truthy. This can lead to strange results, until converted, e.g. !!truthyValue

Collapse
 
efpage profile image
Eckehard • Edited

It should be noted, that there are some other stumbling blocks in Javascript, that might cause an uexpected behavoir:

1. Dynamic Type conversion

Calculations may cause unwanted behavoir

    if(1+'1' <  5){
        // Always false
    }
Enter fullscreen mode Exit fullscreen mode

In Javascript, 1+'1' = '11', so it is larger than 5.

2. Default operators

You can use a default value for an 'undefined'

let x = localStorage.getItem("DEF") || 5
Enter fullscreen mode Exit fullscreen mode

This works for all stored values, but 0. If you store 0, x will be set to five 5. Same ist true for all values that evaluate to "false", as JS cannot distinguish between undefined, null, false, 0, NaN or "". The only exception is "0", which is not zero....