What are Truthy and falsy values?

Asked

Viewed 775 times

13

What is the difference of true and false for Truthy and falsy in Javascript? These are just values true and false of "third parties", for example of a variable?

2 answers

18


Javascript has a type coercion mechanism: when a value of a certain type is used in a context that expects a different type, an implicit conversion to the expected type occurs.

This is the case of the second example of Francisco’s reply: in if(1) {..., the if expects a boolean value, true or false. How did you receive 1, He will "find a way" to interpret this numerical value as boolean. I put quotation marks on "find a way" because in fact it is not improvised, in the specification of the language exist clear rules for conversions between types. Rules may sometimes not be intuitive, but are clearly defined.

Thus, values Truthy are the ones that result in true when converted to the boolean type, and the falsy (or falsey) are the ones that result in false when subjected to such conversion.

In accordance with conversion table for Boolean in the language specification:

  • Sane Truthy values of Object, Symbol types (entered in ES6), non-empty strings and different numbers of ±0.
  • Sane falsey the values null, undefined, ±0, NaN and empty strings.

This applies to all contexts that expect boolean values, including expressions expected by if, while, for (in the second argument) and by the operator !.

One point that often confuses people is that two values Truthy or falsey are not necessarily equivalent in other contexts. For example, in comparisons with == the conversion rules are different, because the goal of conversion in the context of equality comparison is to match the types on both sides of the operator, not convert to boolean. That’s why it’s common for doubts on cases seemingly bizarre, like this:

if(1)   // entra no if, logo é truthy
if({})  // também entra no if, também é truthy
1 == {} // false!

11

In javascript we have the boolean type variables natively, which can contain true or false. Take an example:

if (true) //Dará "true"

The value true has a boolean type, ie will return true.

But often we want to use a boolean condition at non-boolean values, and these expressions are called truthy and falsey. Take an example:

if (1) //Dará truthy

The value 1 has a whole different kind of 0, ie, will return Truthy.

This kind of thing is very useful to check if a value is 0 or nulo.

See more about this at Wikipedia.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.