Tuesday, May 23, 2006

The equals/assignment bug

I recently found a classic bug in some Javascript code (not my code!):

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