Home >Web Front-end >JS Tutorial >What is the difference between == and === in JavaScript
What we bring to you in this article is to introduce what is the difference between the == and === operators in JavaScript? It has certain reference value. Friends in need can refer to it. I hope it will be helpful to you.
First of all, we need to know: the '==' operator in JavaScript represents abstract equality; And, '====' operator represents strict equality.
Let’s take a lookWhat is the difference between the == and === operators in JavaScript?
The '==' operator performs type conversion of necessary values before performing an equality comparison. To put it simply, the value is converted to the same type first and then compared for equality. Even if the types of the compared values are different, they can be cast to the same type without causing an error.
'====' operator, it does not perform type conversion, so if the two values are not of the same type, then when compared, it will return false. If you compare two variables whose types are incompatible with each other, a compilation error will occur.
Example 1: Comparison of the number 9 and the character "9"
<script> // 字符 "3" 被转换成 数字 3 //因此返回 true document.write(9 == "9"); // 换行 document.write('<br>') // 这里没有类型转换发生, // 因此返回 false document.write(9 === "9"); </script>
Running result:
Example 2: String literals and characters String object comparison
<script> // 字符串对象类型转换为字符串文字 // 因此,返回 true document.write("hello" == new String("hello")); // 换行 document.write('<br>') // 没有进行类型的强制转换 //因此,返回 false document.write("hello" === new String("hello")); </script>
Run result:
Example 3: Boolean type and string
<script> document.write('==:<br>'); // 这里 字符“1” 被转换为true(布尔类型) // 因此,返回 true document.write(true == '1'); document.write('<br>') // 这里 数字1 被转换为true(布尔类型) // 因此,返回 true document.write(true == 1); document.write('<br>') // 没有类型转换,因此 返回 false document.write('==:<br>'); document.write(true === '1'); document.write('<br>') document.write(true === 1); </script>
Run result:
Note:
1. When comparing basic types such as string and number, there is a difference between == and ===
== is to compare "value"; === is to compare "value" and type. The value and type must be consistent to return true.
2. For When comparing advanced types such as Array and Object, there is no difference between == and ===
3. When comparing basic types and advanced types, there is a difference between == and ===
For ==, the advanced type will be converted into a basic type for "value" comparison
For ===, because the types are different, the result is false
Summary:The above is the entire content of this article, I hope it will be helpful to everyone's study.
The above is the detailed content of What is the difference between == and === in JavaScript. For more information, please follow other related articles on the PHP Chinese website!