Blog

Variable Cautions and Gotchas in JavaScript

By Martin Schaeferle | July 23, 2012


Thumbnail for 688

When it comes to JavaScript, there are a few variable cautions and gotchas to be aware of. Keep in mind that although the value stored in a JavaScript variable is strongly typed-a string, number, Boolean, or object-the variable can hold any type during program execution. There is no type defined as part of the declaration. So the following code, although convoluted and probably confusing to maintain, is perfectly legitimate.

Don't do this! Use each variable for a single purpose to make your code clearer and give it a name related to that purpose. In general, you should use each variable for a single type, even though JavaScript doesn't enforce this.

var count = 0; <program code> count = "Don"; <more program code> count = false <yet more code> count = "The Duke of Windsor";

Be careful when splitting a var statement across multiple lines! If you accidentally omit any commas, all of the subsequent variables will be declared as global variables, which pollutes the global namespace and causes hard to find bugs. So, for example, if you omitted the comma after the count variable is declared and initialized, as in the following code, JavaScript injects a semicolon at the end of the first line and the minMsgID and lastName variables will be global variables. (The indenting makes no difference to JavaScript.) This problem is avoided if you have the entire var statement on a single line in the code file or declare each variable in its own statement with the var keyword.

var count = 0 minMsgID = 32629, lastName = "Kiely";

TIP: In ECMAScript 5/Strict mode, it is an error to assign a value to an undeclared variable. But in older versions of the standard, and in ECMAScript 5/Default mode, the variable is declared as a property of the global object as described above. It is legal and generally harmless to declare a variable more than once with the var statement, although it takes extra typing and clutters up your code. If a later, redundant var statement also initializes the variable, it acts as a simple assignment statement. No matter how many times you declare a variable within its scope, you'll have only a single instance of the variable.

Get more JavaScript training Today!



Martin Schaeferle

Martin Schaeferle has taught IT professionals nationwide to develop applications using Visual Basic, Microsoft SQL Server, ASP, and XML. He has been a featured speaker at Microsoft Tech-Ed and the Microsoft NCD Channel Summit, and he specializes in developing Visual Basic database applications, COM-based components, and ASP-based Web sites. In addition to writing and presenting technical training content, Martin is also LearnNowOnline's vice president of technology.


This blog entry was originally posted July 23, 2012 by Martin Schaeferle