1. Technology

Common Javascript Errors

Page 1

By

Businessman working in office
Jetta Productions/Blend Images/Getty Images

When you first try to run a JavaScript on your web page it is quite likely that it wont work the way that it is supposed to. You may get an error message that gives you a clue as to what happens or the script may just not appear to do anything.

There are lots of reasons why a script doesn't work but there are a small number of common errors that people make when writing JavaScript. When your script doesn't work the best place to start if you don't have an error message that tells you exactly what went wrong is to check your code to see if you made any of these more common errors. Chances are that if you check for each of these common errors you will probably find out why your script isn't working or at least rectify some of the problems that were messing it up. You might not find all of the errors but once you have corrected the common ones then it should make the other errors easier to find.

So what common errors should we check for and what can we do to find and fix them?

Mismatched or Misplaced Braces

JavaScript uses braces {} to surround the commands that are to be run as a block. You would use them around the content of a loop to group statements within an if statement. These blocks can be nested within one another when you have multiple if statements or combinations of loops and if statements. When you have these blocks nested several levels deep it becomes very easy to lose track of how many open and close braces that you have, particularly where several blocks all end at once. There should always be a close brace } for every open brace {.

Another possible problem when you have many blocks of code nested within one another is to lose track of what level you are at within the nesting and to end up placing code at the wrong level - which leads to the code not functioning as expected.

The easiest way to rectify problems related to mismatched or misplaced braces is to obtain a print of the code and to use several different highlighting markers to mark the corresponding pairs. Start at the beginning of the code and highlight the first { with one colour. You then move through the code looking for the next { or }. If it is } you mark it with the same colour as the last { and move back to the previous colour highlighter that you used. If a { you get the next colour highlighter and mark it with that. Keep the colours in order to indicate levels of nesting and you will soon be able to see what belongs to which block of code.

  1. About.com
  2. Technology
  3. JavaScript
  4. Problem Solving
  5. Common Javascript Errors and How to Find Them

©2014 About.com. All rights reserved.