OverviewWe know that developers now use === instead of ==, why? Most tutorials I've seen online agree that it's too complicated to predict how JavaScript coercion works, and therefore recommend always using ===. This leads many programmers to exclude parts of the language and view it as a flaw, rather than expanding their understanding of the process. The following two use cases illustrate the benefits of using ==. 1. Test for null valuesif (x == null) vs if (x === undefined || x === null) 2. Read user inputlet userInput = document.getElementById('amount'); let amount = 999; if (amount == userInput) vs if (amout === Number(userInput)) In this article, we’ll take a deep dive into the topic by contrasting the differences, understanding coercion, examining some popular use cases, and finally finding guidelines to guide our decision. IntroductionIn JavaScript, equality is accomplished with two operators. 1. === — Strict equality comparison is also called the triple equality operator. 2. == — Abstract equality comparison I've been using === because I've been told it's better and better than ==, and I don't have to think about it at all, which, as a lazy person, I find convenient. Until I watched "Deep JavaScript Foundations" by Kyle or @getfiy, the author of You Don't Know JS, at Frontend Masters. The fact that, as a professional programmer, 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 care more about the code we write. Where is the root of the fact?It is important to know where the real reason lies. Not on Mozilla's W3school, not in the hundreds of articles claiming === is better than ==, and definitely not in this article. . In the JavaScript specification, we can find documentation about how JavaScript works. Breaking the common sense1. == only checks the value (loose)If you look at the specification, it's pretty clear from the definition that the first thing the algorithm does is actually check the type. 2. === Check value and type (strict)Here again, we can see from the spec that it checks the types, and if they are different, it doesn't check the values again. The real difference between double and triple equals is whether we allow coercion. Coercion in JavaScriptCasting or type conversion is one of the fundamentals of any programming language. This is especially important for dynamically typed languages like JavaScript, because the compiler won't yell at you and fuss with you if the type changes. Understanding imperatives means we can interpret the code in the same way as JavaScript, giving us greater scalability and minimizing errors. Explicit coercionCasting can happen explicitly when the programmer calls one of these methods, thereby forcing a change in the type of a variable. Boolean(), Number(), BigInt(), String(), Object() case: let x = 'foo'; typeof x // string x = Boolean('foo') typeof x // boolean Hide TransformationIn JavaScript, variables are weakly typed, so this means they can be automatically converted (implicitly coerced). This is usually the case when we use arithmetic operators + / — *, surrounding context, or when using ==. 2 / '3' // '3' is forced to be 3 new Date() + 1 // Forced to a date string ending in 1 if(x) // x is coerced to a Boolean value 1 == true // true is coerced to 1 1 == 'true' // 'true' is coerced to NaN `this ${variable} will be coreced to string Implicit coercion is a double-edged sword. Proper use can increase readability and reduce verbosity. We have a formula for disappointment if used improperly or misunderstood, and people will rant and blame JavaScript. Comparison of algorithms== operator algorithm 1. If X and Y are of the same type, === is performed. 2. True if X is null and Y is undefined or vice versa. 3. If one is a number, coerce the other to be a number. 4. If one is an object, cast to the original object. 5. Otherwise, return false. === comparison algorithm 1. If the types do not match false. 2. If the types match - compare the values, and return false if it is NaN. 3.-0 — true. Popular use cases1. Same type (most cases)If the types are the same, === is exactly the same as ==. Therefore, the one with more semantic meaning should be used. 1 == 1 // true ...... 1 === 1 // true 'foo' == 'foo' // true ...... 'foo' === 'foo' //true The types are different, I prefer to use ===. 2. Different types (primitive types)First of all, I want to draw your attention to the fact that different types do not mean unknown types. Not knowing the types indicates a bigger problem in your code than just using === vs ==. Knowing types indicates a deeper understanding of the code, which leads to fewer bugs. Suppose we have the possibility of a number or a string. Remember that the algorithm prefers numeric types, so it will try to use toNumber() let foo = 2; let bar = 32; // number or string foo == bar // If bar is a string, it will be converted to a number foo === Number(bar) // doing basically the same foo === bar // where bar is a string, then the result is false 3. null and undefinedWhen using ==, null and undefined are equal to each other. let foo = null let bar = undefined; foo == bar // true foo === bar // false 4. Non-primitive types [objects, arrays]You should not use == or === to compare non-primitive types such as objects and arrays. Decision-making criteria1. It is best to use == in all situations where it can be used. 2. == With a known type, you can choose to force type conversion. 3. Knowing the type is better than not knowing it. 4. If you don't know the type, don't use ==. 5. === is meaningless when the types do not match. 6. === is unnecessary when types match. Avoid using ==There are some cases where you shouldn't use == without really understanding falsy values in JavaScript. == with 0 or "" or " " == with non primtives == true or == false SummarizeIn my experience so far, I have always known the type of the variable I was dealing with, and if I didn't, I used typeof to only allow the variables I expected. Four points to note 1. If you don't know the variable type, then using === is the only reasonable choice 2. Not knowing the type may mean you don’t understand the code, please try to refactor your code 3. Knowing types allows you to write better code. 4. If the type is known, it is better to use ==. The above is the detailed content about not using the absolute equality operator everywhere in JS. For more information about JS, please pay attention to other related articles on 123WORDPRESS.COM! You may also be interested in:
|
<<: Overview of MySQL Statistics
CentOS6.9+Mysql5.7.18 source code installation, t...
In the process of web project development, we oft...
Table of contents Preface webpack-deb-server webp...
1. Build the basic image of jmeter The Dockerfile...
In the previous article, after configuring the we...
Share the cool front-end page random QR code veri...
If you don't want to use javascript control, t...
Preface binlog is a binary log file, which record...
As a tester, you may often need to install some s...
Project scenario: There is a <ul> tag on th...
location expression type ~ indicates to perform a...
Use Nginx to build Tomcat9 cluster and Redis to r...
1. Check whether port 80 is occupied. Generally, ...
Table of contents Preface text 1. Global Registra...
Preface Recently, I accidentally discovered MySQL...