


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
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
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 }
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
Analysis of typical examples
![] == [] //true
这是一道比较容易令人困惑的题,按照正常的思维模式,对一个操作数逻辑取反,跟这个操作数本身的值是相对的,如果这个操作数本身的值是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!

C and JavaScript achieve interoperability through WebAssembly. 1) C code is compiled into WebAssembly module and introduced into JavaScript environment to enhance computing power. 2) In game development, C handles physics engines and graphics rendering, and JavaScript is responsible for game logic and user interface.

JavaScript is widely used in websites, mobile applications, desktop applications and server-side programming. 1) In website development, JavaScript operates DOM together with HTML and CSS to achieve dynamic effects and supports frameworks such as jQuery and React. 2) Through ReactNative and Ionic, JavaScript is used to develop cross-platform mobile applications. 3) The Electron framework enables JavaScript to build desktop applications. 4) Node.js allows JavaScript to run on the server side and supports high concurrent requests.

Python is more suitable for data science and automation, while JavaScript is more suitable for front-end and full-stack development. 1. Python performs well in data science and machine learning, using libraries such as NumPy and Pandas for data processing and modeling. 2. Python is concise and efficient in automation and scripting. 3. JavaScript is indispensable in front-end development and is used to build dynamic web pages and single-page applications. 4. JavaScript plays a role in back-end development through Node.js and supports full-stack development.

C and C play a vital role in the JavaScript engine, mainly used to implement interpreters and JIT compilers. 1) C is used to parse JavaScript source code and generate an abstract syntax tree. 2) C is responsible for generating and executing bytecode. 3) C implements the JIT compiler, optimizes and compiles hot-spot code at runtime, and significantly improves the execution efficiency of JavaScript.

JavaScript's application in the real world includes front-end and back-end development. 1) Display front-end applications by building a TODO list application, involving DOM operations and event processing. 2) Build RESTfulAPI through Node.js and Express to demonstrate back-end applications.

The main uses of JavaScript in web development include client interaction, form verification and asynchronous communication. 1) Dynamic content update and user interaction through DOM operations; 2) Client verification is carried out before the user submits data to improve the user experience; 3) Refreshless communication with the server is achieved through AJAX technology.

Understanding how JavaScript engine works internally is important to developers because it helps write more efficient code and understand performance bottlenecks and optimization strategies. 1) The engine's workflow includes three stages: parsing, compiling and execution; 2) During the execution process, the engine will perform dynamic optimization, such as inline cache and hidden classes; 3) Best practices include avoiding global variables, optimizing loops, using const and lets, and avoiding excessive use of closures.

Python is more suitable for beginners, with a smooth learning curve and concise syntax; JavaScript is suitable for front-end development, with a steep learning curve and flexible syntax. 1. Python syntax is intuitive and suitable for data science and back-end development. 2. JavaScript is flexible and widely used in front-end and server-side programming.


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

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

Hot Article

Hot Tools

Atom editor mac version download
The most popular open source editor

Dreamweaver Mac version
Visual web development tools

PhpStorm Mac version
The latest (2018.2.1) professional PHP integrated development tool

mPDF
mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

EditPlus Chinese cracked version
Small size, syntax highlighting, does not support code prompt function