The answer is: never use it. This article in turn denies five places that seem to be usable =, and explains why.
There are two operators in JavaScript to determine whether two values are equal:
Strict equality operator ===, must be of the same type and value.
Normal (tolerant) equal operator ==, type conversion is performed first before the comparison value is strictly equal.
The advice for beginners of JavaScript is: completely forget =, always use =. practice has proved that this is completely correct. five cases seem to refute this argument, but they do not. from now on, our guiding principles are:
We prefer code with clear intentions over conciseness.
Remember: Your code is only written once, but it may need to be read many times-Please make your code readable as much as possible.
Case 1: You know what you are comparing
For example, if the typeof operator is used, you can determine that it returns a string. so using = is safe, because we can make sure that such a comparison will not have any type conversion:
- if (typeof x == "function") {
- ...
- }
However, there are two reasons for us not to do this:
Consistency: If you use = here, you will not get any benefits. Why bother using it without breaking the unified rules?
Simplicity and Performance: Generally, the = operation is simpler, because it does not need to convert its operations. in different JavaScript Engines, the performance of this operator varies, but in most browsers, The = ratio is always faster, at least not slower.
Case 2: Compare undefined and null
When using = for comparison, undefined and null are in the same equivalence class-they are equal to themselves, and they are also equal to each other, but it is not equal to any other value (including the false values in JavaScript ):
- > null == null
- true
- > undefined == null
- true
- > false == null
- false
- > 0 == null
- false
Therefore, the following if statement can detect whether x is null or undefined ).
- if (x == null) {
- ...
- }
However, the conciseness of the Code is completely offset by the lack of clear intent in the Code: If you need to check the undefined value, you should also write it. otherwise, if a beginner in JavaScript reads your code, they will find that you are only detecting null. if a veteran reads your code, they may think that you have made a mistake. Here we should use =.
- if (x === undefined || x === null) {
- ...
- }
If your requirements are not so strict, the above Code can be abbreviated
- if (!x) {
- ...
- }
As long as x is the values listed below, the condition detection will pass.
- undefined
- null
- false
- 0
- ""
Note: among the five original value types, each has a false value? No. NaN is missing.
Case 3: compare strings and numbers
The scenario is: you are writing code that interacts with the user interface or code that processes parameters returned by the server. you may need to process string numbers. if x is such a string, you can compare it like this:
- if (x == 123) {
- ...
- }
But why don't I tell the person reading your code that x is not a number? A better way is to convert it into a number and then compare it.
- if (Number(x) === 123) {
- ...
- }
Case 4: Compare object values and original values
Using =, you can compare two original values, or compare an original value with its packaging type object value:
- > function isAbc(x) { return x == "abc" }
- > isAbc("abc")
- true
- > isAbc(new String("abc"))
- true
If yes:
- > new String("abc") === "abc"
- false
The left side of the equal sign is an object value, and the right side is an original value. therefore, they do not have the same type, so they cannot be strictly equal. even so, you should give priority to how to let people who read your code clearly understand the intent of your line of code. if the following statement is used
- x == "abc"
What is the task you want to complete?
Can the value on the left be both a string packaging object and a string original value? This seems unlikely, but if so, you should clearly state in the document what the operation is.
Do you want to convert the object value to the original starting value? So you can write more clearly
- String(x) === "abc"
Do you want to unpack an original value? So you should write it like this.
- x.valueOf() === "abc"
Case 5: JavaScript is flexible-so should the code I wrote.
This argument is as follows: I hope my code will show the same flexibility as JavaScript. and = can help me implement it. the following is an example of JavaScript flexibility. It can automatically convert the value type:
- > "abc" + false
- 'abcfalse'
- > 3 + true
- 4
- > +"73"
- 73
The following are a few redisals of the above arguments:
Standard implicit conversions do not always meet your expectations. For example:
- > !"false"
- false
- > 7 + "3"
- '73'
- > Number("")
- 0
Tolerating equality judgments and common implicit conversions have different manifestations:
- > 2 == false
- false
- > 2 == true
- false
- > Boolean(2)
- true
Explicit type conversion and strict equality judgment can produce more descriptive code. Bad Syntax: use equal tolerance for flexibility
- function is123Implicit(x) {
- return x == 123;
- }
- > is123Implicit(123)
- true
- > is123Implicit(new Number(123))
- true
- > is123Implicit("123")
- true
Alternative method: explicit type conversion plus strict equality to achieve flexibility:
- function is123Explicit(x) {
- x = Number(x);
- return x === 123;
- }
- > is123Explicit(123)
- true
- > is123Explicit(new Number(123))
- true
- > is123Explicit("123")
- true
Who said your code must be flexible? It can be said that the default flexibility of JavaScript is a bug rather than a feature. Writing defensive code can expose these bugs more quickly. A more defensive function is123Explicit () is as follows:
- function is123Defensive(x) {
- if (typeof x !== "number") {
- throw new TypeError("Not a number: "+x);
- }
- return x === 123;
- }
If you want to input a parameter that is not a numeric original value, you must first convert the type.
Conclusion
I hope I have convinced you that we should stick to the principle of simplicity and never use = for judgment. this makes sense, not only for beginners, but also for the code that has less skills, it means that the Code has better readability.