The equals/assignment bug
I recently found a classic bug in some Javascript code (not my code!):
Of course, the code should be
This kind of bug is a real joy to hunt down ;-)
I learned years ago to write the condition in the anti-assignment way. For example, instead of writing
write it
where possible, because the assignment error (using one "=" instead of two) should be caught by the compiler/interpreter in the latter case. I do my best to hold to this, and it has saved me some headaches.
In this case, if you write
you see the error in the Javascript console - "Error: invalid assignment left-hand side".
if (MyObject.isActive = this) {
...
}
Of course, the code should be
if (MyObject.isActive == this) {
...
}
This kind of bug is a real joy to hunt down ;-)
I learned years ago to write the condition in the anti-assignment way. For example, instead of writing
if (x == 3) {...
,write it
if (3 == x) {...
where possible, because the assignment error (using one "=" instead of two) should be caught by the compiler/interpreter in the latter case. I do my best to hold to this, and it has saved me some headaches.
In this case, if you write
if (this = MyObject.isActive) {
...
}
you see the error in the Javascript console - "Error: invalid assignment left-hand side".
0 Comments:
Post a Comment
<< Home