javascriptbooleanfalsytruthy

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?!


Solution

  • 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 ===.