what is the main difference between '=' and '==' operators in javascript?

In JavaScript, the = operator is used for assignment, while the == operator is used for equality comparison. Understanding this difference is fundamental to writing correct JavaScript code.

The Assignment Operator (=)

The = operator assigns a value from the right side to the variable on the left side. It does not compare values.

<html>
<body>
<p id="assignment"></p>
<script>
var x = 5;        // Assigns 5 to variable x
var y = "6";      // Assigns string "6" to variable y
var z = x;        // Assigns value of x (5) to variable z

document.getElementById("assignment").innerHTML = 
"x = " + x + "<br>" +
"y = " + y + "<br>" +
"z = " + z;
</script>
</body>
</html>
x = 5
y = 6
z = 5

The Equality Operator (==)

The == operator compares two values for equality. It performs type coercion, meaning it converts values to the same type before comparison.

<html>
<body>
<p id="comparison"></p>
<script>
var a = 5;
var b = "5";      // String "5"
var c = 6;

document.getElementById("comparison").innerHTML = 
"a == b: " + (a == b) + "<br>" +    // true (5 == "5")
"a == c: " + (a == c) + "<br>" +    // false (5 == 6)
"b == c: " + (b == c);              // false ("5" == 6)
</script>
</body>
</html>
a == b: true
a == c: false
b == c: false

Key Differences

Operator Purpose Returns Example
= Assignment Assigned value x = 5 assigns 5 to x
== Equality comparison Boolean (true/false) 5 == "5" returns true

Common Mistake

A frequent error is using = instead of == in conditions:

<html>
<body>
<p id="mistake"></p>
<script>
var num = 10;

// Wrong: assignment instead of comparison
if (num = 5) {
    document.getElementById("mistake").innerHTML = "This will always execute because assignment returns the assigned value (5)";
}

// Correct: comparison
// if (num == 5) {
//     document.getElementById("mistake").innerHTML = "This would not execute";
// }
</script>
</body>
</html>
This will always execute because assignment returns the assigned value (5)

Conclusion

Remember: = assigns values, while == compares values. Always use == (or === for strict comparison) in conditional statements to avoid unexpected behavior.

Updated on: 2026-03-15T23:18:59+05:30

314 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements