JavaScript programs may generate unexpected results if a programmer accidentally uses an assignment operator (=
), instead of a comparison operator (==
) in an if statement.
This if
statement returns false
(as expected) because x is not equal to 10:
var x = 0;
if (x == 10)
if (x == 10)
This if
statement returns true
(maybe not as expected), because 10 is true:
var x = 0;
if (x = 10)
if (x = 10)
This if
statement returns false
(maybe not as expected), because 0 is false:
var x = 0;
if (x = 0)
if (x = 0)
An assignment always returns the value of the assignment.
Practice Excercise Practice now