Home >Web Front-end >JS Tutorial >What's the Difference Between =, ==, and === in JavaScript?
Understanding the Differences between =, ==, and === in JavaScript
When coding in JavaScript, it's crucial to understand the distinct roles and usage of the assignment operator =, the comparison operator ==, and the identity operator ===.
Assignment Operator (=)
The = operator assigns a value to a variable. The syntax is variable = value. For instance, let age = 25; sets the variable age to 25. The result of the assignment operation is the value assigned, in this case, 25.
Comparison Operator (==)
The == operator compares two values for equality. It loosely compares values, attempting to coerce them to the same type if necessary. If the values are equivalent after coercion, it returns true; otherwise, it returns false. For example, 5 == '5' returns true because the string '5' can be coerced to the number 5.
Identity Operator (===)
The === operator performs a strict comparison, checking both the type and value of the operands. If both operands are identical in type and value, it returns true; otherwise, it returns false. Unlike ==, it doesn't attempt to coerce the values to the same type. For example, 5 === '5' returns false because the string '5' is not of the same type as the number 5.
Example
The provided code snippet reads:
if($("#block").css.display == "none"){ $("#block").css.display = "block"; }
Here, the assignment operator = is used to set display to "block" when the condition is met. In contrast, the comparison operator == is used to check if display is set to "none" before changing it.
Additional Resources
For a quick introduction to JavaScript, check out CodeCademy. For more in-depth reading, refer to MDN (Mozilla Developer Network).
The above is the detailed content of What's the Difference Between =, ==, and === in JavaScript?. For more information, please follow other related articles on the PHP Chinese website!