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 following code attempts to use a variable before it has been initialized:

alert(someVariable); // error

Always make sure to initialize a variable with a value before attempting to use it.

Similarly, be sure to pass arguments to functions that require a value. Consider the following code:

function addByTwo(num) {
    return num + 2;
}

var result = addByTwo();

alert(result); // NaN

This code defines a function called addByTwo(), which accepts a single argument. The function returns the value of the parameter plus two. The final two lines of this code call addByTwo(), assigning the result to the result variable and alerting result. When addByTwo() is called in this code, JavaScript assigns the value of undefined to the num parameter because no value was passed to it. Since undefined is not a number, the addition operation fails and results in NaN. In general, failing to pass a required value to a function will result in the function's failure.

In addition, you must ensure that function definitions that do have parameters correctly use the parameters' identifiers in the function body. Take a look at the following code:

function someFunction(someParameter) {
    alert(someParamter);
}

someFunction("Hello, World!");

This code has an error. The someFunction() declaration defines a parameter called someParameter. However, this parameter isn't used within the function's body. Instead, the alert() method attempts to alert the value of someParamter (notice the missing e between m and t). A slight typo, such as the omission of one letter, can cause your code to fail. Be mindful of your identifiers, and make sure they match their definitions.

CASE-SENSITIVITY

Slight typos are a nuisance. Just like omitting a single character, not matching an identifier's case can result in your code's failure. For example, see if you can spot all the errors in the following code:

var myName = "Jeremy";
If (myname === "Jeremy") {
    alert(myName.toLowercase());
}

There are three errors in this code:

  • The capitol I in If should be lowercase.

  • The myname identifier is all lowercase when the n should be capitalized.

  • The toLowercase() method doesn't exist. Instead, the code should call toLowerCase().

Always be aware of case; knowing the identifier naming conventions can help with that:

  • All keywords and reserved words are lowercase.

  • All variables, non-constructor functions, properties, and methods begin with a lowercase letter and use camel-case afterward.

  • All data type constructor identifiers begin with an uppercase letter and use camel-case afterward.

CLOSING BRACES AND PARENTHESES

Code organization is key to maintainability and readability, and JavaScript has two built-in organizational units with curly braces and parentheses. Unfortunately they are not enough; you need to use whitespace to make code a little easier to read. Following is code that has a few deliberate mistakes. See if you can spot them:

function doSomething()
{
var x=1,y=2;
if (x+y)*2<10)
{
if (x+y<5)
{
alert("Alert something");
}
}

doSomething();

This code is a mess, and it is a good illustration of why you should strive to format your code. Formatting makes code easier to read, which in turn makes errors easier to identify. So let's format the code as follows:

function doSomething() {
    var x = 1,
        y = 2;

    if (x + y) * 2 < 10) {
        if (x + y < 5) {
            alert("Alert something");
        }
    }

doSomething();

Now you can easily identify one of the errors: A closing curly brace is missing at the end of the function definition. The second error is a bit trickier to find. Look at the first if statement and you'll notice that there is one opening parenthesis and two closing parentheses. An opening parenthesis needs to be added to properly enclose the addition operation. It's very easy to miss an opening or closing parenthesis if you have many parentheses in one statement.

Following is the corrected code with corrections in bold:

function doSomething() {
    var x = 1,
        y = 2;

    if ((x + y) * 2 < 10) {
        if (x + y < 5) {
            alert("Alert something");
        }
    }
}

doSomething();

OPERATOR MISUSE

It's common to misuse an operator, especially when dealing with assignment (=) and equality (==). Look at the following example:

var number = 100;

if (number = 200) {
    alert("Number is 200");
} else {
    alert("Number is " + number);
}

At first glance you might think the result of this code will be an alert box displaying the message "Number is 100". That is not the case. This code illustrates the very common mistake of using the assignment operator instead of the equality operator. Instead of comparing number with the literal of 200, the code inside the if statement's condition assigns number the value of 200.

What makes misuse like this worse is that JavaScript doesn't throw an error. Assigning a value to a variable inside a condition is perfectly valid, so the only indication you get is abnormal behavior from your application. In a large chunk of code, operator misuse is very easy to overlook. So keep it in mind if your script behaves differently from how you expected.

Note

Please select Lesson 36 on the DVD to view the video that accompanies this lesson.

OPERATOR MISUSE
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.142.40.32