Common Javascript Errors

Page 1

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.

Mismatched Quotes or Apostropies

With HTML and Javascript you can surround text strings with either quotes (") or apostrophes ('). To keep things straight particularly when you have HTML code within document.write statements you should standardize on using quotes for HTML and apostrophes for Javascript. If you do this you will have no problem with statements such as document.write('<a href="mypage.htm">'); since the quotes are fully nested within the apostrophes.

There are two possible problems here. You might accidentally leave out a closing apostrople leading to the following statements ending up as part of the text string and therefore having the code not function. The other possibility is that you might need to include an actual apostrophe in the text. In order for an apostrophe within the text to not be treated as the end of the text it needs to be "escaped" by preceding it with a backslash like this document.write('Let\'s go.');.

Leaving out a closing apostrophe or forgetting to escape one within the text both lead to a mismatch and the code not functioning correctly. You can check for this error using a printout of your code and three highlighters. Use the first colour to mark the start of text, the second to mark escaped apostrophes and the third to mark end of text and you will soon spot any that are mismatched.

Parentheses Missing Around If Condition.

When you code an if statement you need to place parentheses () around the condition(s) that you are testing with the if statement.

Where you have multiple conditions that you are testing in the one if statement you may also need to surround parts of the condition test with parentheses as well in order to make sure that the conditions are evaluated in the right order. It is easy to forget to include these parentheses and if you have many of them nested within one another it is easy to lose track of how many levels of nesting that you have open.

Like with the braces around blocks of code, using a highlighting marker to mark the various levels of nesting in a really complex if statement should soon help you see if you have misplaced one or left one out.

Missing Semi-colon.

Each Javascript statement should end with a semi-colon. Sometimes you see Javascript code where each statement is on a separate line and the semi-colons have been left off but if you need to rearrange the code for any reason you will soon find that it stops working if you end up with two statements on the same line and have forgotten to add in the semi-colon.

The simplest way to resolve this problem is to reformat your code so that each statement appears on a separate line and make sure that each line ends with a semi-colon.

You can always combine lines together gradually after you get the code working.

Capitalization mismatch.

Javascript is case sensitive. This means that myvar and myVar are two separate variables. To avoid creating a problem with referring to the wrong variable due to capitalization errors I suggest that you adopt a standard approach to naming your variables by either capitalizing the first letter of the second and subsequent words in the variable name eg. thisIsMyVariable or by separating the words with underscores eg. this_is_my_variable. This will avoid the possibility of your creating two variables whose names only differ in the capitalization used and will make it more obvious when you are looking for errors that the variable name has been specified with the incorrect capitalization.

Another problem if you do name two variables the same is that not all browsers correctly implement the case sensitivity and will treat variables that differ only in capitalization as being the same variable which can result in code with incorrectly capitalized variable names working in some browsers but not others.

Referencing Objects Before They are Loaded.

Javascript code that is placed in the head section of your page that is not contained within functions will be run before the page loads. Javascript in the body of the page will execute as that part of the page is loaded. Javascript called from the onload event handler will run after the page has finished loading. Functions will run when they are called from anywhere else in the Javascript code.

Event handlers will run when the associated event is triggered.

If your Javascript is accessing the content of your web page via the document object model then those objects that you are referencing must have already loaded before you can reference them. Referencing an object that hasn't finished loading yet will give an error. To rectify this problem you should make sure that you don't try to reference any objects on the page from Javascript that is in the head section of the page unless it is contained in a function that gets called after the page finishes loading. References to objects from Javascript that is in the body of your page may work intermittently depending on the order in which the Javascript and the object that is referred to get loaded.

To rectify these problems move the processing of the object to the onload event handler for the web page.

Reserved Word Used as Variable Name

There are a number of words that have a special meaning to the Javascript language.

These reserved words cannot be used as variable or function names. If you inadvertently use a reserved word as a variable name then the results of your processing will not be what you expect.

The best way to avoid this is to become familiar with the reserved word list so that you know what words to avoid.

If you choose and follow an appropriate naming standard for your variable names you will be able to avoid using reserved words as variable names because your standard naming convention will make sure that they don't get used.

Missing Parameter on Function Call

When you define a function you define the number of arguments that the function is expecting to receive. When you write the code to call the function you need to pass the appropriate parameters expected by the call. It is relatively easy to check how many parameters that a function expects to receive when you are coding a call to that function. If the arguments have been given reasonable names it should also be reasonably obvious what needs to be passed in each parameter.

Where this becomes a possible problem is if you decide to add an extra argument to the function. All calls to this function now need to be updated to pass the extra parameter. If the function is in an external Javascript that is linked into many of the web pages on your site then it is easy to miss a call to the function from one of the pages.

Unsupported Document Object Model

The W3C standard document object model is supported by most modern browsers including Internet Explorer 5+, Opera 5+, and Netscape 6+. Presumably you are using one of these browsers yourself and so scripts that are coded to use the standard DOM will work when you test them in your browser. Some of your visitors may be running earlier browsers such as Internet Explorer 4 or Netscape 4. If you want your script to support these visitors as well then you will need to code your script to use the cross browser DOM.

There are many scripts that can be downloaded from the internet that date back to the IE4/NS4 days and so the scripts only support those browsers and more recent versions of Internet Explorer (that still support the IE4 DOM for backwards compatibility).

These scripts will not function on browsers other than Internet Explorer and/or Netscape 4.

To rectify this problem you should rewrite the script to use the standard DOM or cross browser DOM instead of the IE4/NS4 specific ones.

You can tell if a script uses the old DOMs if it references document.all or document.layers.

Format
mla apa chicago
Your Citation
Chapman, Stephen. "Common Javascript Errors." ThoughtCo, Oct. 29, 2015, thoughtco.com/common-javascript-errors-2037670. Chapman, Stephen. (2015, October 29). Common Javascript Errors. Retrieved from https://www.thoughtco.com/common-javascript-errors-2037670 Chapman, Stephen. "Common Javascript Errors." ThoughtCo. https://www.thoughtco.com/common-javascript-errors-2037670 (accessed November 20, 2017).