Pages

Thursday, December 29, 2011

Be careful when creating JavaScript variables on the server side

Writing JavaScript from your server-side code can be a great way to create a dynamic, flexible site. But you should also be aware of the risks. For example, suppose you generate your variable names from product codes stored in the database. While this may be a great scheme, what do you do if the database entry is "", a number, a duplicate of a previous entry, or a reserved word? Any of those circumstances could cause your JavaScript variable to be invalid.

To make such an automatic coding scheme work, you need to make sure your code checks for anything that will cause improper JavaScript to occur. Remember also that when generating variable names, it's safer to append something at the beginning so that the variable doesn't start with a number. This is important because it's common for errors or other unforeseen circumstances to result in a function returning a number, such as 0. That will cause a JavaScript error since JavaScript variables can't start with a number.

Another thing to watch out for is differences between what the server-side code generates in a development environment as compared to a production environment. Lots of puzzling situations have resulted because the same JavaScript seemed to work for the developer but not for the client. Well, wait a minute, was it really the same JavaScript? Different environment means different variables means a different Web page. And of course, Murphy's law instructs us that the combination of factors most likely to cause a problem are found in the production environment, not the testing environment.

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.