Hacker Newsnew | past | comments | ask | show | jobs | submitlogin

> == is bad. Don’t ever use it.

Could someone expound for the ignorant?



Lazy response, excerpted from a blog post[1]:

One particular weirdness and unpleasantry in JavaScript is the set of equality operators. Like virtually every language, JavaScript has the standard ==, !=, <, >, <=, and >= operators. However, == and != are NOT the operators most would think they are. These operators do type coercion, which is why [0] == 0 and "\n0\t " == 0 both evaluate to true. This is considered, by sane people, to be a bad thing. Luckily, JavaScript does provide a normal set of equality operators, which do what you expect: === and !==. It sucks that we need these at all, and === is a pain to type, but at least [0] !== 0.

[1]: Post from my blog, but I'm not linking to it because the rest is not useful to answer this question and I don't want to come across as a self-promoting-link-whore :)


It is not self promotion if someone asks for it. So how about a link.




If the two sides of the comparison have different types, JavaScript tries to coerce the values using rules that are pretty strange. The recommendation I've heard most often is to always prefer === and !==.




Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: