Coding with JavaScript For Dummies
Book image
Explore Book Buy On Amazon

Even the best JavaScript programmers make mistakes. Sometimes, these mistakes cause your program to not produce the results that you wanted, and sometimes they cause the program to not run at all. Here are ten common mistakes that JavaScript programmers at all levels often make.

Equality confusion

Does x equal y? Is x true? The questions of equality are central to JavaScript and can seem quite confusing. They revolve around three areas in JavaScript: namely conditional statements and operators (if, &&, and so on), the equals operator (==), and the strict equals operator (===).

To complicate coding even more, the assignment operator (=) looks ­suspiciously like what most people call an equals sign. Don’t be fooled!

Avoiding misuse of assignment

The assignment operator assigns the operand on the right to the operand on the left. For example:

var a = 3;

This statement gives the new variable, named a, the value of 3.

An operand is anything in a program. Think of it as similar to a noun in ­language, whereas operators (+,-,*,/ and so on) are like verbs.

Assignment operators may also have expressions on the right side, which are evaluated and then assigned to the variable on the left.

A common mistake that beginners to the language make is to mistake assignment for comparison — for example:

if (a=4){.. .}

This code won’t run as expected if what you expected is to compare the value of a to the number 4.

Dodging the equals pitfalls

The equals operator (==) and its evil twin the not equals operator (!=) can be quite flexible, but also quite dangerous. Use it as little as possible, if at all. Here’s why:

0 == ‘0’

Everyone who’s spent any time programming knows that a number inside of quotes isn’t really a number. But the == operator considers them to be the same, because it will make the two values the same type prior to comparing. This can lead to all sorts of problems that are difficult to track down.

If you do want to compare a string with a number and get a result of true if they appear the same, it’s much safer to do this explicitly as follows:

parseInt(0) === parseInt("0")

This statement also evaluates to true, but there is no voodoo magic involved. The strict equals (===) and the strict not equals (!==) will do exactly what you would expect.

0 === ‘0’

The two operands are clearly different types, and the result is false.

Mismatched brackets

As a program becomes more complicated, and especially when you’re working with JavaScript objects, the brackets start to pile up. Here’s a JavaScript object with mismatched brackets:

{
 "status": "OK",
 "results": [{
  "id": 12,
  "title": "Coding JavaScript For Dummies",
  "author": "Chris Minnick and Eva Holland",
  "publication_date": "",
  "summary_short": "",
  "link": {
   "type": "review",
   "url": "",
   "link_text": "Read the New York Times Review <br/>of Coding JavaScript For Dummies"
  },
  "awards": [{
   "type": "Nobel Prize",
   "url": "",
   }]
}

Can you see the problems here? When this happens, a good code editor can be invaluable! Sublime Text has a feature that will show you a brackets match when you place your cursor next to either a starting or ending bracket.

Highlighting matching brackets in Sublime Text.
Highlighting matching brackets in Sublime Text.

Mismatched quotes

JavaScript allows you to use either single quotes or double quotes to define strings. However, JavaScript is not at all flexible with the rule that you must end your string with the same type of quote you started with. Also, look out for quotes and apostrophes in strings that are the same characters as the quotes surrounding the string! For example:

var movieName = "Popeye’; // error!
var welcomeMessage = ‘Thank you, ‘ + firstName + ‘, let’s learn JavaScript!’ // error!

Missing parentheses

This error most often crops up in conditional statements, especially those in which there are multiple conditions. Consider this example:

if (x > y) && (y < 1000) {
...
}

What you want to do here is check that both of the conditions are true. However, there are actually three conditions at work here, and they all need parentheses. What’s missing in the preceding example is the parentheses around the big && condition, which says that both of the other conditions must be true in order to proceed with the code between the brackets.

In order to be correct, this statement should read as follows:

if ((x > y) && (y < 1000)) {
...
}

Missing semicolon

JavaScript statements should always end with a semicolon. However, if you put each statement on its own line and leave off the semicolons, the code will still run as if the semicolons are there. Even though the code still runs, ­leaving off the semicolon can lead to problems when you rearrange code or when two statements end up on the same line somehow.

The best way to avoid this error is to always use a semi-colon at the end of a statement.

Capitalization errors

JavaScript is case-sensitive. This means that the variables you create need to be capitalized exactly the same every time you use them. It also means that functions need to be capitalized correctly in order to work.

One of the most common places to see this error happen is with the getElementByld method of the Document object. You would think that it would be spelled getElementBylD because that would make more grammatical sense, but it isn’t correct!

Referencing code before it’s loaded

JavaScript code normally loads and runs in the order that it appears in a document. This can create problems if you reference HTML that’s positioned later in the document from a script that’s in the head of the document.

Referencing HTML before it is loaded results in an error.
Referencing HTML before it is loaded results in an error.
<html>
<head>
 <script>
 document.getElementById("myDiv").innerHTML = "This div is my div";
 </script>
</head>
<body>
 <div id = "myDiv">This div is your div.</div>
</body>
</html>

This code will result in an error because at the time the JavaScript runs, the browser doesn’t yet know about the div with the id = myDiv that comes later in the web page.

In order to avoid this issue, you have a couple of options:

  • Place your JavaScript at the bottom of your HTML file, right before
    .

  • Put your JavaScript code into a function. Then you can call the function using an onload event attribute in the starting body tag.

The problem was resolved here using the second method.

Wait until the HTML is loaded before running the script.
Wait until the HTML is loaded before running the script.
<html>
<head>
 <script>
 function nameMyDiv() {
 document.getElementById("myDiv").innerHTML = "This div is my div";
 }
 </script>
</head>
<body onload = "nameMyDiv();">
 <div id = "myDiv">This div is your div</div>
</body>
</html>

Bad variable names

One particularly hard-to-track-down rule is the prohibition against using reserved words as variable names.

Interestingly, JavaScript has over 60 reserved words and many others that you just shouldn’t use as variable names. Rather than memorizing all of the reserved words, the best way to avoid these types of naming errors is to simply come up with a more descriptive naming scheme that is highly unlikely to ever cross paths with a reserved word.

For example, the word name is one of JavaScript’s reserved words. If you get into the habit of being specific with what you’re naming, you’ll name variables for storing things, such as firstName, lastName, dogName, and nameOfTheWind; thus totally avoiding conflicts with reserved words.

Scope errors

JavaScript has function scope and global scope. If you declare a variable without using the var keyword, that variable will have global scope and will be usable anywhere in your program. The results can be detrimental to your program. In order to avoid scope errors, make sure to always use the var keyword to create new variables.

Missing parameters in function calls

Whenever you create a function, you declare the number of parameters that should be passed to that function when it’s called. Calling the wrong number of functions won’t always result in an error in JavaScript, but it can produce unexpected results if the code within the function requires parameters that aren’t present.

Make sure to give your parameters descriptive names when you create a function and double-check every time that a function is called in order to make sure that the right number of parameters is passed.

Counting errors: Forgetting that JavaScript counts from 0

If you count to 10 in a JavaScript array, you’ll actually have 11 items. Never forget that the first item in an array has an index of 0.

Forgetting that JavaScript counts from 0 can lead to unexpected results.
Forgetting that JavaScript counts from 0 can lead to unexpected results.
var myArray = new Array();
myArray[10] = "List of 10 Common Mistakes";
myArray.length; // produces 11!

About This Article

This article is from the book:

About the book authors:

Chris Minnick is an accomplished author, trainer, and web developer who has worked on web and mobile projects for both small and major businesses. Eva Holland is an experienced writer and trainer who has designed and taught online, in-person, and video courses. They are cofounders of WatzThis?

This article can be found in the category: