Home Web Front-end JS Tutorial A brief discussion on the equality operator in JavaScript: the difference between == and ===

A brief discussion on the equality operator in JavaScript: the difference between == and ===

Jun 13, 2020 am 09:33 AM
js

A brief discussion on the equality operator in JavaScript: the difference between == and ===

In the process of programming, we often encounter the situation of judging whether two variables are equal. ECMAscript provides two equality operators "==" and "===" To judge, both operations will return a boolean value. Generally speaking, we call "==" equal and "===" congruent.

When the data types of the two compared variables are consistent, the situation is relatively simple. However, when the variable types on both sides of the operator are inconsistent, or even one of the variables is an object, the situation is more complicated. As follows Introduce separately what will happen to the operation results when the operand types are different.

Congruent operator “===”

Congruent operator “===” The situation is relatively simple. When using the congruence operator "===" to judge, first check whether the data types of the operands on both sides of the operator are consistent. If they are inconsistent, false will be returned directly. Otherwise, the next step of judgment will be made.

If it is a comparison of two booleans, then both sides of "===" must be both true or false before it can return true, otherwise it will return false. If the two comparisons are numbers, then only if True will be returned only when the two numbers are equal in size, otherwise false will be returned.

If the two variables to be compared are strings, first compare the lengths of the two strings to see if they are equal. If the lengths are different, return false. If they are equal, start from the first of the two variables. The characters start to be compared for equality and continue until the last digit; if one of the digits does not want to wait, false is returned, otherwise true is returned.

(Note: The comparison of strings will not ignore spaces, so when comparing two strings to see if they are equal, to ensure safety, you should first remove the spaces, and then convert the two strings to uppercase Or lowercase and then compare).

null will only return true if null===null, otherwise it will return false. Similarly, undefined will only return true if undefined===undefined, otherwise it will return false. . For example:

true === 1    //false
"1" === 1    //false
 
//boolean的比较
true === true  //true
true === false  //false

//string的比较
"hello" === "helloworrld" //false
"hello" === "world" //false
"hello" === " hello" //false
"hello" === "hellO" //false
"hello" === "hello" //true

//number的比较
1 === 1  //true
1 === 1.0 //true
1 === 1.2 //false

//null和undefined的比较
undefined === undefined  //true
null === null       //true
undefined === null    //false,两者在"=="时才返回true
Copy after login

If the two operands for "===" comparison are not basic type values, but two objects, the basis for judgment at this time is to judge whether the two variables are "the same" Object

var a,b,c;
a = b = {
	name : '柳轻侯',
	city : '南京'
};
c = {
	name : '柳轻侯',
	city : '南京'
};
a === b   //true
a === c   //false
Copy after login

It is not enough for two objects to "look the same". a and c are both Object instances, and they have the same properties and values, but they are not the "same" object. , because a and c actually point to two different instances, so the two objects are not congruent.

But a and b point to the same object. In other words, a and b are different aliases of the same object. They actually point to the exact same object, so a === b. The comparison rules for "!==" and "===" are the same and will not be repeated here.

Equality operator”==”

When the congruence operator makes a judgment, if the types of the two variables are different, then Directly returns false, but unlike this, when the "==" equality operator is judging, if the types of the two variables are different, an implicit type conversion will be performed to convert the two values ​​​​to be compared into the same Types are compared again, so what are the conversion rules?

When converting different data types, the equality and inequality operators follow the following basic rules

  • If one of the operands is a boolean value, it will be compared before comparison The boolean value is converted to a number value, true is converted to 1, and false is converted to 0;
  • If one of the operands is of string type and the other is of number type, the string type is converted to number before comparison. The type is then judged;
  • Before comparison, undefined and null will not be converted to other values ​​for comparison;
  • If one of the operands is an object and the other is a basic type value , then the object is converted to a basic type value before comparison, and then subsequent comparisons are made according to the previous rules;

The two operands follow the following rules when comparing

  • undefined and null are equal, that is: undefined == null;
  • If one operand is NaN, then false is returned. Even if both operands are NaN, false will be returned;
  • If the two operands are objects, the comparison rules are the same as the comparison rules of "===". Unless the two operands are the same object, then return true, otherwise return false;

It should be noted here that NaN == NaN returns false. NaN means not a number, which means that the operand is a non-number. This non-number is uncertain. It The value of is unknown, and may not even be expressed using JavaScript syntax. Such an unknown quantity cannot be used for specific comparisons. If you cannot determine what the value of two unknown things is, of course you cannot say NaN == NaN.

So since we cannot use "==" to compare, how do we determine whether a variable is NaN? Since we cannot use equality to determine, then we might as well do the opposite and use "!=" Determine whether a variable is not equal to NaN. For example:

//如果需要判定一个变量是不是NaN,可以如下
//a是你需要判定的变量
if((typeof a === "number") && a != NaN ){  //此处需要注意,NaN也是number类型
	//TODO 
}
Copy after login

Common comparison situations and their results

null == undefined  // true 
"NaN" == NaN    // false 
5 == NaN      // false 
NaN == NaN     // false 
NaN != NaN     // true 
false == 0     // true 
true == 1      // true 
true == 2      // false 
undefined == 0   // false 
null == 0      // false
"5" == 5      // true
Copy after login

Analysis of typical examples

![] == [] //true
Copy after login

这是一道比较容易令人困惑的题,按照正常的思维模式,对一个操作数逻辑取反,跟这个操作数本身的值是相对的,如果这个操作数本身的值是true,那么取反之后就是false,反之,如果这个操作数的值是false,那么对其逻辑取反之后就是true,无论如何也不会是同一个值,可是事实上却是![] == []。

首先,![]的值是false,因为这里[]被当成了一个数组的实例,是一个对象,而对象都是真值,对其取反,得到一个假值,也就是false。

其次看等号右边,[]是一个对象,要将其转为基本类型值,会先调用数组的valueOf方法,而数组的valueOf方法返回数组本身,没有得到一个基本值。

这时候要继续调用数组的toString方法,得到一个””空字符串,所以这时候也就变成了false == “”是否为真的问题了,而根据前面的规则,如果有一个操作数为boolean值,会将其转为数值,false转化为0。

进而,问题转化为0 == “”是否为真值的问题,当number和string比较时,会将string转为number,而””会转为0。最后,问题变演化成了0 == 0是否为真值,毋庸置疑,结果是true。

这里要注意的就是![],它被当成了一个整体的逻辑值,是直接对对象进行取反,是一个假值,而不是先把[]转化为基本值再取反

小结

“==”在比较不同类型值得时候会进行隐式的类型转化,而”===”不会转化,全等一定相等,相等却不一定全等,这是一个充分不必要条件。

undefined和null相等而不全等,且在相等比较的时候不会转化为其他类型的值。NaN是不等于NaN 的,要判断某个变量是不是NaN,要用”!=”。对象和非对象在进行比较的时候会先转为基本类型值然后再根据上面的规则进行比较。

推荐教程:《JS教程

The above is the detailed content of A brief discussion on the equality operator in JavaScript: the difference between == and ===. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How to use JS and Baidu Maps to implement map pan function How to use JS and Baidu Maps to implement map pan function Nov 21, 2023 am 10:00 AM

How to use JS and Baidu Map to implement map pan function Baidu Map is a widely used map service platform, which is often used in web development to display geographical information, positioning and other functions. This article will introduce how to use JS and Baidu Map API to implement the map pan function, and provide specific code examples. 1. Preparation Before using Baidu Map API, you first need to apply for a developer account on Baidu Map Open Platform (http://lbsyun.baidu.com/) and create an application. Creation completed

Recommended: Excellent JS open source face detection and recognition project Recommended: Excellent JS open source face detection and recognition project Apr 03, 2024 am 11:55 AM

Face detection and recognition technology is already a relatively mature and widely used technology. Currently, the most widely used Internet application language is JS. Implementing face detection and recognition on the Web front-end has advantages and disadvantages compared to back-end face recognition. Advantages include reducing network interaction and real-time recognition, which greatly shortens user waiting time and improves user experience; disadvantages include: being limited by model size, the accuracy is also limited. How to use js to implement face detection on the web? In order to implement face recognition on the Web, you need to be familiar with related programming languages ​​and technologies, such as JavaScript, HTML, CSS, WebRTC, etc. At the same time, you also need to master relevant computer vision and artificial intelligence technologies. It is worth noting that due to the design of the Web side

Essential tools for stock analysis: Learn the steps to draw candle charts with PHP and JS Essential tools for stock analysis: Learn the steps to draw candle charts with PHP and JS Dec 17, 2023 pm 06:55 PM

Essential tools for stock analysis: Learn the steps to draw candle charts in PHP and JS. Specific code examples are required. With the rapid development of the Internet and technology, stock trading has become one of the important ways for many investors. Stock analysis is an important part of investor decision-making, and candle charts are widely used in technical analysis. Learning how to draw candle charts using PHP and JS will provide investors with more intuitive information to help them make better decisions. A candlestick chart is a technical chart that displays stock prices in the form of candlesticks. It shows the stock price

How to create a stock candlestick chart using PHP and JS How to create a stock candlestick chart using PHP and JS Dec 17, 2023 am 08:08 AM

How to use PHP and JS to create a stock candle chart. A stock candle chart is a common technical analysis graphic in the stock market. It helps investors understand stocks more intuitively by drawing data such as the opening price, closing price, highest price and lowest price of the stock. price fluctuations. This article will teach you how to create stock candle charts using PHP and JS, with specific code examples. 1. Preparation Before starting, we need to prepare the following environment: 1. A server running PHP 2. A browser that supports HTML5 and Canvas 3

How to use JS and Baidu Maps to implement map heat map function How to use JS and Baidu Maps to implement map heat map function Nov 21, 2023 am 09:33 AM

How to use JS and Baidu Maps to implement the map heat map function Introduction: With the rapid development of the Internet and mobile devices, maps have become a common application scenario. As a visual display method, heat maps can help us understand the distribution of data more intuitively. This article will introduce how to use JS and Baidu Map API to implement the map heat map function, and provide specific code examples. Preparation work: Before starting, you need to prepare the following items: a Baidu developer account, create an application, and obtain the corresponding AP

How to use JS and Baidu Map to implement map click event processing function How to use JS and Baidu Map to implement map click event processing function Nov 21, 2023 am 11:11 AM

Overview of how to use JS and Baidu Maps to implement map click event processing: In web development, it is often necessary to use map functions to display geographical location and geographical information. Click event processing on the map is a commonly used and important part of the map function. This article will introduce how to use JS and Baidu Map API to implement the click event processing function of the map, and give specific code examples. Steps: Import the API file of Baidu Map. First, import the file of Baidu Map API in the HTML file. This can be achieved through the following code:

PHP and JS Development Tips: Master the Method of Drawing Stock Candle Charts PHP and JS Development Tips: Master the Method of Drawing Stock Candle Charts Dec 18, 2023 pm 03:39 PM

With the rapid development of Internet finance, stock investment has become the choice of more and more people. In stock trading, candle charts are a commonly used technical analysis method. It can show the changing trend of stock prices and help investors make more accurate decisions. This article will introduce the development skills of PHP and JS, lead readers to understand how to draw stock candle charts, and provide specific code examples. 1. Understanding Stock Candle Charts Before introducing how to draw stock candle charts, we first need to understand what a candle chart is. Candlestick charts were developed by the Japanese

How to use JS and Baidu Maps to implement map polygon drawing function How to use JS and Baidu Maps to implement map polygon drawing function Nov 21, 2023 am 10:53 AM

How to use JS and Baidu Maps to implement map polygon drawing function. In modern web development, map applications have become one of the common functions. Drawing polygons on the map can help us mark specific areas for users to view and analyze. This article will introduce how to use JS and Baidu Map API to implement map polygon drawing function, and provide specific code examples. First, we need to introduce Baidu Map API. You can use the following code to import the JavaScript of Baidu Map API in an HTML file

See all articles