Stop using absolute equality operators everywhere in JS

Stop using absolute equality operators everywhere in JS

Overview

We 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 values

if (x == null)
vs
if (x === undefined || x === null)

2. Read user input

let 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.

Introduction

In 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 sense

1. == 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 JavaScript

Casting 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 coercion

Casting 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 Transformation

In 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 cases

1. 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 undefined

When 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 criteria

1. 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

Summarize

In 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:
  • JavaScript operators explained in detail never before
  • Summary of uncommon js operation operators
  • JavaScript Basics Operators
  • Summary of uncommon operators and operators in js
  • Summary of some efficient magic operators in JS
  • Let's take a look at the same old JS operator explanation

<<:  Overview of MySQL Statistics

>>:  Detailed explanation of how to enable HSTS in nginx to force the browser to redirect to HTTPS access

Recommend

Deploy grafana+prometheus configuration using docker

docker-compose-monitor.yml version: '2' n...

Summary of principles for writing HTML pages for emails

Since HTML email is not an independent HOST page o...

MySQL 8.0.24 version installation and configuration method graphic tutorial

This article records the installation and configu...

Detailed explanation of desktop application using Vue3 and Electron

Table of contents Vue CLI builds a Vue project Vu...

HTML table markup tutorial (22): row border color attribute BORDERCOLORLIGHT

Within rows, light border colors can be defined i...

The most comprehensive collection of front-end interview questions

HTML+CSS 1. Understanding and knowledge of WEB st...

Using js to realize dynamic background

This article example shares the specific code of ...

Understanding MySQL precompilation in one article

1. Benefits of precompilation We have all used th...

Detailed explanation of using pt-heartbeat to monitor MySQL replication delay

pt-heartbeat When the database is replicated betw...

Detailed explanation of the use of Join in Mysql

In the previous chapters, we have learned how to ...

How to upgrade MySQL 5.6 to 5.7 under Windows

Written in front There are two ways to upgrade My...

CSS easily implements fixed-ratio block-level containers

When designing H5 layout, you will usually encoun...