Tuesday, March 27, 2012

The pitfalls of JavaScript and a need for strict code reviews

Look at the difference between these 2 JavaScript function

Code A

function foo()
{
    name = "f";
}
Code B

function foo()
{
    var name = "f";
}


Code A attempts to access and set a global variable named "name" while Code B, because it include "var", creates a new, function scope variable called name and sets this.

It is a known pitfall that every JavaScript developer gets warned about but it is also a mistake that is very easy to make and very hard to catch, at least by hand.

This is one reason why, although a powerful web tool, JavaScript is a terribly dangerous language and I suggest you employ code reviews of the strictest kind. Sorry Douglas, although I enjoy your lectures and enthusiasm immensely and your book is very useful, JavaScript is seriously flawed, and this is just one example. By the way, for those interested in learning JavaScript, Douglass' lectures are a must see!

Here is how badly such 3 characters can effect a business

In Realm Of Empires, which runs inside Facebook's iFrame, we wanted to implement correct high sizing to eliminate scroll bars. To accomplish this, we had to use external Facebook JavaScript API FB.Canvas.setAutoResize.

For 3 years, developer after a developer have attempted to implement correct iFrame resizing for Realm Of Empires. For some reason, it did not work, no errors, no clues. In each case we abandoned this effort as we simply could not justify more time.

In the latest attempt just recently, I was determined to get it fixed and slowly started stripping down the pages to bare bones.I found that at some point the Facebook API started working. I narrowed it down to a couple of scripts that, when included, would break the code. I was still puzzled why those scripts prevented the code from working, and they were both not small or trivial.

Thankfully, a comment game me a clue needed! Someone said that renaming a global variable from name to username fixed their issue. I searched and found 2 instances where a global variable "name" was used instead of a function-scope one.

We would have found the issue sooner if we had dedicated more time, if we did a more thorough review of our JavaScript code, perhaps if we used some code review tools but the bottom line is that JavaScript does allow this mistake and you have to be on guard as this could have serious consequences

LESSON LEARNED
check and double check your JavaScript code! There are lots of automated code review tool that you will find helpful.


No comments:

Post a Comment