Why is 'false' truthy in javascript?

空扰寡人 提交于 2019-12-01 19:00:24

问题


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?


回答1:


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.




回答2:


is there anything explicit in the specification?

Yes:

The result is false if the argument is the empty String (its length is zero); otherwise the result is true.




回答3:


In Javascript any string that is not empty is truthy.

So, when evaluating any non-empty string results in true even when the string itself is 'false'.

You can read more about truthy and falsy values.

If you want to check a string for truthness, you can check it's length.

var val = str.length > 0;



回答4:


The value of a non-empty string is always true.

Boolean(false) returns false

Boolean('false') returns true




回答5:


It's by definition. It's a string and it is handled as such. No matter the meaning of the string.

If your logic would be applied. Then how about following examples:

"1+3==2"
"humans have four eyes"

Are they also falsy?



来源:https://stackoverflow.com/questions/32720503/why-is-false-truthy-in-javascript

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!