Home >Web Front-end >JS Tutorial >The difference between = and == in js
The = and == operators in JavaScript serve different purposes. = is the assignment operator, used to assign a value to a variable, while == is the comparison operator, used to compare two values for equality, regardless of type. In general, it is recommended to use the strict equality operator === because it compares both values and types to avoid unexpected equality comparison results.
The difference between = and == in JavaScript
In JavaScript, =
and ==
are two different operators used for different purposes.
Assignment Operator (=)
=
The operator is used to assign a value to a variable or property. For example:
<code class="js">let x = 10; const y = "Hello";</code>
The above code assigns the value 10
to the variable x
, and assigns the string "Hello" to the constant y
.
Comparison Operator (==)
==
The operator is used to compare whether two values are equal. It only compares the value of two values, regardless of type. For example:
<code class="js">console.log(10 == "10"); // true console.log(false == 0); // true</code>
The above code outputs true
, because the values of 10
and "10"
are equal, and false
and The values of 0
are also equal.
Difference
=
is the assignment operator, used to assign values. ==
is a comparison operator used to compare whether values are equal. ==
does not consider the type, while ===
compares whether both value and type are equal. Usage Recommendations
Normally, it is recommended to use the strict equality operator ===
because it not only compares values; Compare types. This avoids unexpected equality comparison results. For example:
<code class="js">console.log(10 === "10"); // false console.log(false === 0); // false</code>
The above code outputs false
, because 10
and "10"
have different types, false
and The types of 0
are also different.
The above is the detailed content of The difference between = and == in js. For more information, please follow other related articles on the PHP Chinese website!