When is it OK to use == in JavaScript?

equality, javascript, operators

Solution

If you're sure that it won't do any "conversion shenanigans", as per your example, then yes, you should still use `===`, because you'll save the parser the effort of having to work out whether it needs to do a conversion. So you'll get better performance. (marginal, but still)

This isn't about security; it's about performance and about doing things the right way.

The only time you should use double equal is where you know in advance that you definitely do want to use javascript's implicit type conversion. This might be the case for example if you want to check the numeric value of an input field (which would be string). But even then, in a lot of cases you would be better to convert the value manually first.

In short, use the `===` syntax everywhere unless you are certain that you need the implicit conversion functionality of `==`.

Problem

From: http://www.2ality.com/2011/12/strict-equality-exemptions.html JavaScript has two operators for determining whether two values are equal: - The strict equality operator === only considers values equal that have the same type. - The “normal” (or lenient) equality operator == tries to convert values of different types, before comparing like strict equality. The advice given to JavaScript beginners is to completely forget about == and to always use ===. But what is the reason behing it for not using == operator? Will it result to security risk? But using typeof operator we can be sure that the result will be a string. Then == is safe to use, because we can be sure that it won’t perform any conversion shenanigans: ``` if (typeof x == "function") { ... } ```

Original source