Understanding Truthy Falsy in javaScript

Hello & Welcome to my first Blog on javaScript. I’m entirely truthy to you that after reading this article you’ll understand what truthy falsy is in javaScript 😀.

There’s some place in javaScript that requires a Boolean value. for instance, if-else, switch case statement expects a Boolean value. If we pass a non-boolean value to them then JS engine converts the given value to either truthy or falsy.

Truthy is not a real Boolean true but works like true.

Falsy is not a real Boolean false but works like false.

Let’s visualize it.

So if our isAdult variable’s value is true then the code inside the if block will run and if it’s false, code inside the else block will run.

Here we are passing isAdult variable to if else statement and isAdult variable’s value is Boolean true. Instead of passing a Boolean value we also can pass a non-boolean value and javaScript engine will convert it to either truthy or falsy.

Let’s see how it works.

So we are passing a non-boolean value to the if statement which is a string with length. Although it’s not a Boolean (true/false) value, javaScript engine thinks that as this is a string with a length let’s convert it to truthy and run the code inside the if statement.

If there was an empty string in the dinner variable, javaScript would convert it to falsy and run the code inside the else statement.

So what are all the stuffs that can be convert to truthy

All Other Things that’s not truthy is falsy

Let’s write a code to identify whether our value is falsy or truthy

In values array we put values we want to know whether it’s truthy or falsy and loop through each value with forEach method and in loop we write a if else statement, if the value is truthy the code inside if block will run and if not then code inside else will run.

So that’s it for today, i hope you feel less confused now than ever about truthy falsy in javaScript.

I believe that the best way to improve skills is sharing. If something went wrong please show me what went wrong, where went wrong, I’ll be happy to learn something new from you 😘.

Front End Developer

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store