首页 > 其他分享 >== vs === in js

== vs === in js

时间:2023-04-27 12:22:57浏览次数:41  
标签:comparison return operands type number js vs true

Equality comparisons and sameness - JavaScript | MDN (mozilla.org)

Loose equality is symmetric: A == B always has identical semantics to B == A for any values of A and B (except for the order of applied conversions). The behavior for performing loose equality using == is as follows:

  1. If the operands have the same type, they are compared as follows:
    • Object: return true only if both operands reference the same object.
    • String: return true only if both operands have the same characters in the same order.
    • Number: return true only if both operands have the same value. +0 and -0 are treated as the same value. If either operand is NaN, return false; so NaN is never equal to NaN.
    • Boolean: return true only if operands are both true or both false.
    • BigInt: return true only if both operands have the same value.
    • Symbol: return true only if both operands reference the same symbol.
  2. If one of the operands is null or undefined, the other must also be null or undefined to return true. Otherwise return false.
  3. If one of the operands is an object and the other is a primitive, convert the object to a primitive.
  4. At this step, both operands are converted to primitives (one of String, Number, Boolean, Symbol, and BigInt). The rest of the conversion is done case-by-case.
    • If they are of the same type, compare them using step 1.
    • If one of the operands is a Symbol but the other is not, return false.
    • If one of the operands is a Boolean but the other is not, convert the boolean to a number: true is converted to 1, and false is converted to 0. Then compare the two operands loosely again.
    • Number to String: convert the string to a number. Conversion failure results in NaN, which will guarantee the equality to be false.
    • Number to BigInt: compare by their numeric value. If the number is ±Infinity or NaN, return false.
    • String to BigInt: convert the string to a BigInt using the same algorithm as the BigInt() constructor. If conversion fails, return false.

Traditionally, and according to ECMAScript, all primitives and objects are loosely unequal to undefined and null. But most browsers permit a very narrow class of objects (specifically, the document.all object for any page), in some contexts, to act as if they emulate the value undefined. Loose equality is one such context: null == A and undefined == A evaluate to true if, and only if, A is an object that emulates undefined. In all other cases an object is never loosely equal to undefined or null.

In most cases, using loose equality is discouraged. The result of a comparison using strict equality is easier to predict, and may evaluate more quickly due to the lack of type coercion.

 

== vs === in js

In JavaScript, == and === are comparison operators that are used to compare two values. However, they have different behaviors and are used in different situations.

The == operator is known as the "loose equality" operator. When using ==, JavaScript will attempt to convert the operands to a common type before making the comparison. This means that operands of different types may be considered equal if they have the same "value" after being converted to a common type. For example, the following code will evaluate to true:

console.log(5 == "5"); // true

In this case, JavaScript will convert the string "5" to the number 5 before making the comparison. This behavior can be useful in some cases, but can also lead to unexpected results if not used carefully.

 

The === operator is known as the "strict equality" operator. When using ===, JavaScript will only consider the operands to be equal if they are of the same type and have the same value. For example, the following code will evaluate to false:

console.log(5 === "5"); // false

In general, it is recommended to use === in most cases, as it is more predictable and less error-prone than ==. However, there may be cases where == is more appropriate or necessary, such as when comparing values of different types that are known to have equivalent values after conversion.

 

5 == "5"  vs "5"==5 in js

In JavaScript, both 5 == "5" and "5" == 5 are comparison expressions using the loose equality operator (==).

The expression 5 == "5" evaluates to true because the == operator coerces the string "5" to a number before comparison. This is known as type coercion. Since both operands are now numbers and have the same value, the expression returns true.

The expression "5" == 5 also evaluates to true for the same reason: the == operator coerces the number 5 to a string before comparison. The resulting comparison is "5" == "5", which is true.

It's worth noting that although type coercion can be convenient in some cases, it can also lead to unexpected behavior and bugs. That's why it's generally recommended to use the strict equality operator (===) instead of ==, which does not perform type coercion and is more predictable.

 

so the right part of == always convert to the type on left part?

In JavaScript, when using the loose equality operator (==), the operands may be coerced (converted) to a common type before comparison. The coercion rules for == are somewhat complex, but generally speaking, the following steps are taken:

  1. If the operands are of the same type, perform a strict equality comparison (===), and return the result.
  2. If one operand is null and the other is undefined, return true.
  3. If one operand is a boolean, convert the other operand to a boolean and return the result of the comparison.
  4. If one operand is a string and the other is a number, convert the string to a number and return the result of the comparison.
  5. If one operand is an object and the other is a primitive value, convert the object to a primitive value (using the valueOf() and/or toString() methods) and return the result of the comparison.
  6. Otherwise, the operands cannot be coerced to a common type, so return false.

So, to answer your question: it's not always the case that the right operand is converted to the type of the left operand. In some cases, such as when comparing a boolean and a number, the left operand may be coerced to the type of the right operand instead. The coercion rules for == can be tricky to understand and can lead to unexpected behavior, so it's generally recommended to use the strict equality operator (===) instead.

 

If one operand is a string and the other is a number, convert the string to a number and return the result of the comparison.
it conflicts this: The expression "5" == 5 also evaluates to true for the same reason: the == operator coerces the number 5 to a string before comparison. The resulting comparison is "5" == "5", which is true.

 

You are correct that the behavior I described regarding comparing a string and a number with the == operator is oversimplified. Let me clarify:

When the == operator is used to compare a string and a number, the string is first coerced into a number, and then the comparison is performed. For example, "5" == 5 is true because "5" is coerced to the number 5, and then 5 == 5 is true.

Similarly, when the == operator is used to compare a number and a string, the number is first coerced into a string, and then the comparison is performed. For example, 5 == "5" is also true because 5 is coerced to the string "5", and then "5" == "5" is true.

So in both cases, the operands are coerced to a common type before comparison, and the result of the comparison is based on that common type. I apologize for the confusion in my previous response.

 

 

标签:comparison,return,operands,type,number,js,vs,true
From: https://www.cnblogs.com/chucklu/p/17358571.html

相关文章

  • vue中实际代码模拟JS中promise调接口的运行流程
    假设我们有一个需要调用接口的场景,我们可以使用Vue中的axios库来发送请求。以下是一个简单的例子://引入axios库importaxiosfrom'axios'//定义一个函数,用于发送请求functionfetchData(){//返回一个Promise对象returnnewPromise((resolve,reject)=>{//发......
  • 安装多个NodeJS windows上安装多个Nodejs版本 解决vue2/vue3同时运行
    第一步下载nvm-windowsnvm-windows下载地址:Github最新下载地址进入之后直接下载第二步安装NVM注意路径一定不要包含空格中文否则会报错注意安装路径一定不要包含空格中文否则会报错 点击安装之后如果之前安装了nodejs的话会提示希望nvm管理已安装node版本吗点击是......
  • @JsonFormat和@DataFormat注解解决前后端日期格式一致性问题
    场景分析场景1:当我们从数据库中查询某篇博客文章数据时,blog表中文章发布日期blog_date这个字段,如果未经过处理,后端查询到的数据传到前端进行展示时,会得到一个不太符合我们要求的日期格式,比如:"blog_date":"2020-12-01T14:25:31.296+0000",为了解决这个问题,将后端返回给前端的日......
  • 原生JS模拟超链接在新窗口打开链接
    可用于点击<li>、<span>等元素动作1functionopenNewWindow(url){2vara=$("<ahref='"+url+"'target='_blank'>"+url+"</a>").get(0),3e=document.createEvent('MouseEvents&......
  • vscode 开启html代码自动补全
    divvscode提供了Emmet语法来进行一些代码补全操作,需要在设置中加入"emmet.triggerExpansionOnTab":true即可.打开文件->首选项->设置打开设置界面,    点击右上角的打开设置(json),添加进去就可以,然后我们输入div,按两次Tab键就可以看到自动补全了<div></di......
  • 前端隐藏和显示div的方式js和beetle:
    方式一:设置元素style对象中的display属性1、vart=document.getElementById('demo');//选取id为test的div元素2、t.style.display='none';//隐藏选择的元素3、t.style.display='block';//以块级样式显示方式二:设置元素style对象中的visibility属性1、vart=documen......
  • 【单例设计模式原理详解】Java/JS/Go/Python/TS不同语言实现
    简介单例模式(SingletonPattern)属于创建型设计模式,这种模式只创建一个单一的类,保证一个类只有一个实例,并提供一个访问该实例的全局节点。当您想控制实例数目,节省系统资源,并不想混用的时候,可以使用单例模式。单例有很多种实现方式,主要分为懒汉和饿汉模式,同时要通过加锁来避免线程......
  • Node.js Buffer All In One
    Node.jsBufferAllInOneBuffer.fromhttps://nodejs.org/api/buffer.html#bufferArrayBufferhttps://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBufferhttps://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Glo......
  • How to use axios.js instead of request.js to get data as a buffer All In One
    Howtouseaxios.jsinsteadofrequest.jstogetdataasabufferAllInOne如何使用axios.js代替request.js获取数据作为缓冲区questionconstfs=require("fs");varpath=require("path");const{exit}=require("process");//requ......
  • VS Code+platformio配置ESP32-S3-N16R8(8MB PSRAM + 16MB FLASH)工程
    一、现有问题platformio现有的板子库里面没有ESP32-S3-N16R8(8MBPSRAM+16MBFLASH)的开发板模型,直接强行套用,要么就是解锁不了8MBPSRAM,要么就下载后运行不起来。但是Arduino可以正常解锁。二、简单解决办法先选用esp32-s3-devkitc-1作为开发板模型,在它的基础上做额外的修改:......