The behavior of the
operator (loose equal computing) in the javascript is often confusing. Its secret is that it prefers numerical comparison. At first glance, this seems strange, but once you understand its working principle, you will understand the reasons behind this behavior and how to use it effectively. ==
The operational symbol follows the ==
abstract comparison algorithm . This algorithm has an obvious bias: it prefers to convert the value to numbers before comparison. The working principle is as follows:
==
Important
==
Here, the string "5" is converted into numbers 5, which is relatively successful. However, if you use , the type must be matched, so it returns false.
<code class="language-javascript">console.log(5 == "5"); // true</code>
can handle it without the need to explicit type conversion. ===
==
Although is usually safer, in some cases,
==
Here, Allows functions to process string and digital input without the need for additional type checking logic. ===
==
A wider perspective ==
<code class="language-javascript">function isAnswerCorrect(userInput, correctAnswer) { return userInput == correctAnswer; } console.log(isAnswerCorrect("42", 42)); // true</code>
==
==
The operational symbols in JavaScript have numerical priority. Understanding this can help you write better and predictable code. Although is usually a safer choice, in specific scenarios, if the type of compulsory conversion is intentional and easy to understand, we should consider using ===
because it is also part of the language. ==
The above is the detailed content of We should understand `==` more, than not using it at all.. For more information, please follow other related articles on the PHP Chinese website!