Home  >  Article  >  Web Front-end  >  Should I use "==" or "===" in JavaScript? Answer

Should I use "==" or "===" in JavaScript? Answer

高洛峰
高洛峰Original
2016-11-26 13:19:201286browse

=== should be used in most cases. x == null can only be used when detecting null/undefined, because usually we do not distinguish between null and undefined, that is, x == null is regarded as x === null || x == = Abbreviation for undefined. The comparison of

== seems to be more convenient, such as 1 == '1' , but it will also cause hidden dangers, such as making wrong assumptions about types.

Example:
if (x == 10) x += 5 www.2cto.com

If the incoming x is the string '10', the result of x will become '105'. The string '105' may be transformed in subsequent operations, thereby introducing hidden errors.

In addition, programmers may unconsciously rely on certain assumptions - for example, equality comparison should be transitive, that is, a = b, b = c, should lead to a = c. But JavaScript's == is not transitive. For example, 0 == '0' , 0 == '' , but '0' != '' .

So JS’s == is not Java/C#’s equals(), because the Java/C# language requires equals() to ensure transitivity.

In short, for large-scale programming, the small convenience of == cannot be compared with the risks it brings.

Suggestion:

Forget ==, just use ===. ==It's a design mistake. It will try to perform type conversion (not Java's equal, it is well defined), and the rules of type conversion are difficult to remember. And also breaks transitivity.
Just use ===,! ==, your life of writing javascript will be more comfortable


Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn