O'Reilly logo

JavaScript® 24-Hour Trainer by Jeremy McPeak

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Chapter 36. Common Coding Mistakes

If there's one thing a novice and a guru have in common, it's that they both make mistakes when writing code. They could introduce a bug that is difficult to find and fix, or something as simple as a typo. As an application's code base grows in size, the chances for the developer to make a mistake increase.

There are some common mistakes that all developers make—even professionals. Mistakes are inevitable, but you can minimize the number of common ones you make by watching out for them as you code.

The majority of mistakes covered in this lesson are syntax mistakes. Most syntax mistakes are reported by the browser, but some, as you'll see, don't cause the browser to throw any errors.

UNDEFINED VARIABLES

JavaScript goes out of its way to be accommodating to developers. It inserts semicolons at the ends of statements if you omit them, and it allows you to assign a value to a variable without first declaring the variable with the var keyword. For example, the following code creates a new global variable called myVariable and initializes it with a string value:

myVariable = "Hello, Global!";

While this code executes without any type of error, it is considered bad practice to omit the var keyword from variable declarations. Omitting the var keyword has an effect on the variable's scope—namely, making the variable global. So always use var when declaring a new variable.

Using a variable before it has been given a value results in an error. For example, the ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required