javascriptcastingbooleantruthiness

Why is 'false' truthy in javascript?


I understand that an empty string is falsy in javascript and a not-empty string is truthy in javascript.

However, why is 'false' truthy in javascript, is there anything explicit in the specification? Is it a performance issue or are there situations where you would want the string 'false' to represent true?


Solution

  • Replying to the last part of your question:

    Are there situations where you would want the string 'false' to represent true?

    Let's consider I am testing for empty strings in my user input. To achieve that, I issue:

    if (!theInput) {
        // Do something.
    }
    

    Now do I want that condition to be true if the user enters false in the text box? Of course, I don't.