I saw assign…

..and it fucked up my code, I saw assign. Ten points for anyone who gets the pop reference, and an extra five for those who get the pun.

Take a peek at this snippet of JavaScript code and tell me why it bails out in line 7 with a nasty “foo.bar is not a function” type error despite the explicit check against null:

1
2
3
4
5
6
7
8
9
var foo = {
	isBar: function() { ... }
}
 
// do stuff with foo
 
if ((foo =! null) && foo.isBar()) {
	...
}

Of course, stripped down to less than ten lines and with all the confusing stuff like callbacks, inheritance or asynchronous function calls removed, the error is blatantly obvious to see: it’s a simple typo. Instead of “foo != null” I wrote “foo =! null” and that is equivalent to “foo = !null“, which is an assignment and effectively throws foo away and replaces it with the value of !null (which happens to be true). And, sure enough, true.bar() doesn’t really work all that well. Classic case of PEBCAK.

The irony in this is that just a couple of days ago I was talking to my roomie about how some people consider it good style to do boolean expressions with variables “backwards” like such:

if (500 == $x) { ... }

The argument being that it prevents errors like the one shown above since “500 = $x” blows up in your face right away with a syntax error. We basically agreed that it looks stupid and is, in essence, retarded.

Fifteen minutes of tedious debugging and an considerable amount of profanity later I am starting to think maybe those guys were onto something after all.

No Responses to “I saw assign…”
Sorry, the comment form is closed at this time.