Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
820 views
in Technique[技术] by (71.8m points)

boolean - In JavaScript, why is "0" equal to false, but when tested by 'if' it is not false by itself?

The following shows that "0" is false in Javascript:

>>> "0" == false
true

>>> false == "0"
true

So why does the following print "ha"?

>>> if ("0") console.log("ha")
ha
Question&Answers:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Tables displaying the issue:

truthy if statement

and == truthy comparisons of all object types in javascript

Moral of the story use === strict equality displaying sanity

table generation credit: https://github.com/dorey/JavaScript-Equality-Table


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...