Understanding Truthy Falsy in javaScript

Meer Estiyak
3 min readFeb 20, 2021

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.

let isAdult = true;if(isAdult){
console.log(‘Drink Beer 🍺’);
}else{
console.log(‘Drink Juice 🥤’)
}
// output is: "Drink Beer 🍺"

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.

let dinner = ‘biriyani’;if(dinner){
console.log(‘Start Dinner 🍴’)
}else{
console.log(‘Order Dinner Online 🚲’)
}
// output is: "Start Dinner 🍴"

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

[]  (empty string){}  (empty object)1   (number)-10 (negative number)"string" (string with a length)" " (string with space also truthy as space also a character)

All Other Things that’s not truthy is falsy

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

let  values = [1,-1, 0, 'full string', ' ', '', [], {}, null, undefined];values.forEach(value => {
if(value){
console.log(`${value} is truthy`);
}else{
console.log(`${value} is falsy`)
}
})

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 😘.

--

--