DEV Community

talent
talent

Posted on

JavaScript's true and false: Truthy and Falsy

When you code, and you have to write an if statement like lines below:

if (x_value){
  //some code here
}
Enter fullscreen mode Exit fullscreen mode

what do you think is logically correct value of the x_value? Either true or false, right?

In Javascript though, you'll see some condition where true and false is not used in a boolean context but something else. Look at this code for example:

let name='Alex';
if(name){
   console.log("Hi ",name);
}

Enter fullscreen mode Exit fullscreen mode

in the line you see conditional statement if(name). While it requires boolean expression, name provided there is not a boolean value. It is a string, yet it is a valid expression. Why?

Because implicitly, Javascript do a type coercion, an implicit type conversion, so the string 'Alex' will be converted to boolean value, true.

An expression that will get type coercion to a true value is considered a Truthy value, while expression which will get type coercion to a false value is considered a Falsy value.

Bellow are some expression that Javascript consider as Truthy value when it comes to a boolean context:

//a non empty string
if ('false'){// 'false' is not an empty string, it has content 'false'
  //code here will be executed
}
//an object either with or without properties
if ({} /* or {value: 0} */){// object with no property
  //code here will be executed
}
//an array either empty or has some values
if ([] /* or [1,2,3] */){// array with no or some items
  //code here will be executed
}
//a number other than 0
if (-1 /* or 5 or 0.2 or -100 or Infinity or -Infinity */){// non zero number
  //code here will be executed
}```



In contrast to Truthy values, here are some sample expressions of Falsy value:

`if ("")//empty string
if (null)//null value
if (0 /* or -0 */) //zero number
if (undefined)//undefined value
if (0n)
if (NaN)
`


Enter fullscreen mode Exit fullscreen mode

In practice you'll find yourself love the usage of Truthy and Falsy value because you can shorten your code and made them more clean as well. You'll also find this used a lot in people's code, so understand this concept will definitely help you grow better as a software developer.

Top comments (0)