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.
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.
<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