Truthful and false values

4

What's the difference between true and false (directly speaking) to truthy and falsy in JavaScript? Are only true and false values of "third party", for example of a variable?

    
asked by anonymous 24.01.2018 / 22:36

2 answers

6

In javascript we have the boolean variables natively, which can contain true or false . Here's an example:

if (true) //Dará "true"

The value true has a boolean type, that is, it returns true.

But we often want to use a Boolean condition on non-Boolean values, and these expressions are called truthy and falsey . Here's an example:

if (1) //Dará truthy

The value 1 has an integer type, that is, it returns truthy.

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

See more about this at Wikipedia .     

24.01.2018 / 22:49
5

JavaScript has a type coercion mechanism: When a value of a given type is used in a context that expects a different type, an implicit conversion occurs for the expected type.

This is the case of the second example of Francisco's answer: In% with_%, if(1) {... expects a Boolean value, if or true . Since it received false , it will "find a way" to interpret this numeric value as boolean. I put quotation marks in the "fix" because it is not really unexpected, in the language specification there are clear rules for cross-type conversions. The rules sometimes may not be intuitive, but are clearly defined.

Thus, truthy values are those that result in 1 when converted to the boolean type, and falsy (or falsey ) are those that result in true when submitted to this conversion.

As conversion table for Boolean in the language specification :

  • truthy values of the types Object, Symbol (introduced in ES6), non-empty strings and numbers other than false .
  • False values ±0 , null , undefined , ±0 , and empty strings.

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

One point that confuses people is that two values truthy or falsey are not necessarily equivalent in other contexts. For example, in comparisons with% with% conversion rules are other since the purpose of the conversion in the context of equality comparison is to match the types on both sides of the operator, and not to convert to boolean. That's why it's common for questions about cases seemingly bizarre , like this:

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