- Stop Using === Everywhere
- Seifeldin Mahjoub
- The Nuggets translation Project
- Permanent link to this article: github.com/xitu/gold-m…
- Translator: Zavier
- Proofreader: Chorer, Long Xiong
This is an unusual point of view, let’s explore it!
Most developers prefer to use === instead of ==, why?
Most tutorials I’ve seen online agree that JavaScript’s cast mechanism is too complex to predict results correctly, and suggest using ===.
Many tutorials on the Internet offer incorrect information and opinions. In addition, many Lint rules and well-known websites have a stubborn preference for using ===.
This has led many programmers to understand it not as part of the syntax, but as a syntax flaw.
Here I will give two examples of the use of == to support my point.
- A null value judgment
if (x == null)
vs
if (x === undefined || x === null)
Copy the code
- Reading user input
let userInput = document.getElementById('amount');
let amount = 999;
if (amount == userInput)
vs
if (amout === Number(userInput))
Copy the code
In this article, we will take a look at some common examples to delve into the differences, understand the cast mechanism, and ultimately form a guideline to help us decide whether to use === or ===.
introduce
In JavaScript, there are two operators that can help us determine equality.
= = =
— The strict equality operator (trisection).= =
— The standard equality operator (double equals).
I’ve been using === because I’ve been told it’s better and superior than ==. I don’t need to think about the reason, as a lazy person, I feel very convenient.
Until I read the article “Deep JavaScript Foundations” written by Kyle (Twitter:@getfiy), author of JS You Don’t Know, on Frontend Masters.
As a professional programmer, THE fact that I don’t think deeply about the operators I use every day in my work inspires me to spread awareness and encourage people to understand and pay more attention to the code we write ourselves.
Read the documentation
It may be important to know where the answers lie. It’s not on the Mozilla site, it’s not on the W3schools site, it’s not in any of the articles that claim that === is better than ==, and it’s certainly not in this article.
It’s in the JavaScript specification, where there’s documentation on how JavaScript works. ECMAScript®2020 language specification
Correct cognition
1. == Only make value judgments (loose)
If we look at the documentation, it’s clear by definition that the first thing that == does is actually type checking.
2. === check both type and value (strict)
Here, too, we can see that === checks the type first and, if the type is different, does not check whether the value is the same at all.
So, the difference between double == and triple == is whether we allow casts.
JavaScript cast
Casting is one of the foundations of any programming language. This is even more important for dynamically typed languages, such as JavaScript, because the compiler does not report an error if the type changes.
Understanding casts means that we can explain how JavaScript code works, thus giving us more extensibility and fewer errors.
Explicit conversion
Type conversions can occur explicitly to force a change in the type of a variable when one of the following methods is called:
Boolean()
, Number()
, BigInt()
, String()
, Object()
Such as:
let x = 'foo';
typeof x // string
x = Boolean('foo')
typeof x // boolean
Copy the code
Implicit conversion
In JavaScript, variables are weakly typed, so this means they can be converted automatically (implicitly). For example, when we use the arithmetic operation + / – * in the current context, or when we use ==.
2 / '3' // '3' coerced to 3
new Date() + 1 // coerced to a string of date that ends with 1
if(x) // x is coerced to boolean
1= =true // true coerced to number 1
1= ='true' // 'true' coreced to NaN
`this ${variable} will be coreced to string`
Copy the code
Implicit conversions are a double-edged sword that can be used wisely to make code more readable and less verbose. When used incorrectly or misunderstood, people often howl and blame JavaScript syntax flaws.
Equality judgment algorithm
The standard equality operator ==
- If X and Y are of the same type — execute
= = =
; - If X and Y are one
null
One is theundefined
– returntrue
; - If one is of type number, cast the other.
- If one is an object, cast to the original type;
- In other cases, return
false
.
The strict equality operator ===
- Different types — return
false
; - Same type – compares whether the values are the same (both are
NaN
When to return tofalse
); 0 = = = + 0
– returntrue
.
Common examples
1. Same type (mostly)
If the type is the same, === is exactly the same as ==. Therefore, you should use the more semantic one.
1= =1 // true ...... 1 === 1 // true
'foo'= ='foo' // true ...... 'foo' === 'foo' //true
Copy the code
“I prefer to use ===, just in case the type is different.”
This is not a logical error, it’s like we hit the save button twice and keep refreshing the page. But, just in case, we don’t call the same method twice in our code, do we?
2. Different types (common)
First, I want to remind you that different types do not mean unknown types.
Not knowing the type of the variable indicates that you have a bigger problem in your code than using === or ==.
Knowing the types of variables will give you a deeper understanding of your code, which will help you reduce errors and develop more reliable programs.
By understanding the cast mechanism, we can choose whether to cast or not in cases where we have several possible types, and thus decide whether to use === or ==.
Suppose it’s a number or a string.
Remember that this algorithm prefers to compare the number type, so it will try to use the toNumber() method.
let foo = 2;
let bar = 32; // number 或者 string
foo == bar // If bar is a string, it will be cast to number.
foo === Number(bar) // The principle is similar
foo === bar // If bar is string, always return false
Copy the code
3. The null, and undefined
Null and undefined are equal when == is used.
let foo = null
let bar = undefined;
foo == bar // true
foo === bar // false
Copy the code
4. [Objects, Arrays]
You should not use == or === to compare non-primitive types such as objects and arrays.
guidelines
- Be able to use
= =
Try to use= =
; - Use when you know the type of a variable or when you need to convert the type of a variable
= =
; - It’s better to know the variable type than not;
- Do not use the variable if you do not know the type
= =
; - When I know the type of the variable,
= =
和= = =
It’s the same thing; - When the types are different, use
= = =
Is meaningless; - When the type is the same, use
= = =
Is not necessary;
Avoid the use of= =
In the case
You should avoid using == in some cases without really understanding the falsy value in JavaScript.
= = is followed0or""or""== is followed by a non-primitive type ==trueOr = =false
Copy the code
conclusion
In my experience so far, I always know the typeof variable I’m dealing with when I code, and if I don’t, I use typeof to determine.
Here are four final tips for readers at the end of this article:
- If you cannot know the type of the variable, use
= = =
Is the only reasonable choice; - Not knowing the type of a variable might mean that you don’t understand the code enough, and maybe you need to refactor;
- Knowing the types of variables helps you write better programs;
- This is best used if the type of the variable is known
= =
Otherwise, only use= = =
.
Thank you for reading, and I hope this article helped deepen your understanding of JavaScript. I recommend that you check out the JS series that you don’t know about, because it has an in-depth analysis of JavaScript as a language. You-Dont-Know-JS
If you find any mistakes in your translation or other areas that need to be improved, you are welcome to the Nuggets Translation Program to revise and PR your translation, and you can also get the corresponding reward points. The permanent link to this article at the beginning of this article is the MarkDown link to this article on GitHub.
The Nuggets Translation Project is a community that translates quality Internet technical articles from English sharing articles on nuggets. The content covers Android, iOS, front-end, back-end, blockchain, products, design, artificial intelligence and other fields. If you want to see more high-quality translation, please continue to pay attention to the Translation plan of Digging Gold, the official Weibo, Zhihu column.