DEV Community

Cover image for JavaScript struggles - part 6 | truthy & falsy values
‘Abdelraḥman Dwedar 👨🏻‍💻🇵🇸
‘Abdelraḥman Dwedar 👨🏻‍💻🇵🇸

Posted on • Edited on

JavaScript struggles - part 6 | truthy & falsy values

When we use most of programming languages or scripting languages we have some values that isn't a boolean valaue but it works as so.

We mostly call it truthy & falsy values.

Content table

Truthy Values

Personally I like to think of truthy values as a variable that have an actual value in it.

Sort of messy?
Think of it like that:

  • A value that isn't empty is a valuable value, but when it's empty it's not.

Let's see some examples

We'll use the !! keyword to turn the value into boolean value t check what is the output.

String

console.log(!!"Hello"); // true

let text = "Hi there";
console.log(!!text); // true
Enter fullscreen mode Exit fullscreen mode

Number

console.log(!!18); // true

let num = 88;
console.log(!!num);
Enter fullscreen mode Exit fullscreen mode

Other

Any object ({}) or Array ([]) are truthy values, even if they were empty!!
So be aware if you want to use an object or array for storing, you have to get the values inside of the array or object.


Falsy Values

A falsy value is the opposite of the truthy values.

String

console.log(!!""); // false
Enter fullscreen mode Exit fullscreen mode

Number

console.log(!!0); // false

console.log(!!NaN); // false
Enter fullscreen mode Exit fullscreen mode
To know more about NaN check out the article about numbers

Other

The null object is also falsy value.

console.log(!!null); // false
Enter fullscreen mode Exit fullscreen mode

Use Cases

There's of cause some amazing use cases of knowing this, you can stop a process if the value wasn't a number like so, as if you turned a text into number it turn into NaN and it's a falsy value.

if (inputValue) {
  ... // Actions
}
Enter fullscreen mode Exit fullscreen mode

Thanks for reading I hope you gain new things out of this article 😄

Top comments (0)