Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the difference between truthy and falsy with true and false in JavaScript?

I have a question concerning some concepts in JavaScript such as (truthy, true) and (falsy, false).

I know the type of 1 is not true but the question is: why 1 == true?

What was the main reason of ECMAScript to consider 1 or "ghsagh" as true?

I also cannot understand the meaning of truthy and falsy.

What was the benefit of this consideration?!

like image 512
Amir Jalilifard Avatar asked Feb 11 '15 14:02

Amir Jalilifard


2 Answers

JavaScript likes to convert values to other types implicitly whenever possible. Because of that, when comparing booleans to other types of variables, JavaScript uses the same logic as older programming languages. A value that represents empty, null, or zero (such as 0, or "") evaluates to false, and any other value (such as 1, 5, -19, "ghsfsah", or other meaningful content) evaluates to true.

Why does it do this? Well for one it allows developers a small shortcut when checking to see if a variable has content. For example, if a user doesn't give input in a text field, we can easily check to see if a field is empty and prompt the user.

if ( !textfield.value ) {
    alert( "Please enter something in the text box" );
}

If you need to see if something is actually true or false, you can use ===.

like image 70
David Reeve Avatar answered Nov 14 '22 23:11

David Reeve


JavaScript is very flexible about the types of values it requires. If JavaScript wants a boolean, it will convert whatever value you give it to a boolean.

Some values (“truthy” values) convert to true and others (“falsy” values) convert to false.

The following values convert to, and therefore work like, false:

  1. undefined
  2. null
  3. 0
  4. -0
  5. NaN
  6. "" // the empty string

All other values, including all objects (and arrays) convert to, and work like, true.

As an example, suppose that the variable o either holds an object or the value null. You can test explicitly to see if o is non-null with an if statement like this:

if (o !== null){
....
}

The strict not-equal operator !== compares o to null and evaluates to either true or false. But you can omit the comparison and instead rely on the fact that null is falsy and objects are truthy:

if (o){
....
}

In the first case, the body of the if will be executed only if o is not null. So the code block will execute even if o is set to undefined.

The second case is less strict: it will execute the body of the if only if o is not false or any falsy value (such as null or undefined). Which if statement is appropriate for your program really depends on what values you expect to be assigned to o. If you need to distinguish null from 0 and "", then you should use an explicit comparison.

like image 30
RBT Avatar answered Nov 14 '22 22:11

RBT