JavaScript stack overflow
Here's one that some of you may have seen before, but I thought I'd post it to save some time to those who didn't.
Today we were trying to debug some client-side code and we needed to quickly wire the click event of a button. So we did this, without thinking too hard:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <title>Stack overflow</title> <script type="text/javascript"> function onclick() { // do stuff } </script> </head> <body> <div> <input type="button" value="Click me" onclick="onclick();" /> </div> </body> </html>
Can you spot the stack overflow? We were so focused on the "do stuff" part that we didn't see it at first, thinking it came from there. But of course, it just comes from onclick="onclick();". When JavaScript resolves the name "onclick", it looks first on the current context before it goes up the scope chain and finds our global function (which it never does). The current context here is the input element, which happens to have an "onclick" attribute, which executes "onclick", etc. Crash.
So the valuable lesson we've learned here is to adopt a naming convention for our event handlers that can't conflict with the name of the event. I usually choose elementIdOnEventName. For example here if the input's id is button1, we'd go with button1OnClick.