If you use JavaScript, running into bugs is nearly inevitable. In this tutorial, you will learn about the most common mistakes that might arise from incorrect usage of JavaScript operators and other commands.
We'll also address issues that arise when you don't follow the rules of syntax or misidentify data types. As you learn to correct your errors, you will be able to move on to the advanced JavaScript topics. Even though it can be categorized as JavaScript for dummies, more experienced people are welcome to refresh their memory.
Contents
JavaScript Common Mistakes: Main Tips
- In this tutorial, we will be looking through some of the common mistakes that occur when writing JavaScript and how they may be tackled.
- JavaScript has certain differences that separate it from other programming languages.
- When it comes to bugs, JavaScript for dummies tutorials can be highly helpful for those who already know JavaScript basics.
Wrong Use of Operators
A lot of mistakes that cause beginners a headache are caused by improperly used JavaScript operators. While they are simple to understand and use, they're also easy to mix up: all it takes is one wrong character. We will explain the most common cases and illustrate them with JavaScript code examples so you could memorize the proper usage.
Assignment vs. Comparison Operator
A JavaScript program might yield unwanted results if you confuse the assignment =
and comparison ==
operators in an if
statement. This is one of the rookie mistakes that this JavaScript for dummies tutorial wants you to avoid.
In the example below, the if
statement below will return false
, because the comparison ==
operator checks the value of the a
, thus a
is not equal to 10
:
In the example below, even though a = 1
the if
statement will return true
, because the assignment =
operator will reassign the a
a new value of 10
:
Strict vs. Loose Comparison
Data type does not matter when it comes to loose equality comparisons using ==
operator. The if
statement below will return true
.
This happens because the loose equality comparison operator compares the values after trying to convert the variables into the same type (performing coercion):
However, with strict equality comparison ===
, coercion is not performed, so the data type stays the same and matters to the command. The if
statement below will return false
:
Switch Statements
A rather common mistake is forgetting that switch
statements always use strict equality comparison. The following two JavaScript examples illustrate how an alert is triggered.
In the code example below, switch
will cause an alert
to appear:
var a = 10;
switch(a) {
case 10: alert("This does not look good!");
}
Now, in this next example, the switch
will not cause an alert
to be displayed:
var a = 10;
switch(a) {
case "10": alert("This does not look good!");
}
Addition vs. Concatenation
Addition adds numbers. Concatenation adds strings. The problem is, both operations use the same +
operator in JavaScript.
For this reason, when you add a number as a numeric value, it will give a different result than adding a number in the form of a string:
When you add variables, it may be difficult to predict the results:
var a = 8;
var b = 4;
var c = a + b;
var d = 21;
var e = "0";
var f = d + e;
- Easy to use with a learn-by-doing approach
- Offers quality content
- Gamified in-browser coding experience
- The price matches the quality
- Suitable for learners ranging from beginner to advanced
- Free certificates of completion
- Focused on data science skills
- Flexible learning timetable
- Simplistic design (no unnecessary information)
- High-quality courses (even the free ones)
- Variety of features
- Nanodegree programs
- Suitable for enterprises
- Paid Certificates of completion
- A wide range of learning programs
- University-level courses
- Easy to navigate
- Verified certificates
- Free learning track available
- University-level courses
- Suitable for enterprises
- Verified certificates of completion
Syntax Mistakes
As in every language, grammar rules matter a lot. In English, a comma added or missed might change the meaning of a sentence completely. In JavaScript, though, it might cause bugs and crashes.
Incorrect use of JavaScript syntax might be an easy mistake to make when you're still learning all the rules. We will now explain the most common mistakes, how to easily correct them, and why you should never do them again.
Broken Strings
In JavaScript, you can break a string in your code into two lines:
However, you may not break a string itself right in the middle of it:
You must add a backslash \
in order to break a statement in your code mid-string without affecting the output:
Misplaced Semicolons
In the code below, due to a misplaced semicolon, the code block executes regardless of what the value of x
is:
Broken Return Statements
By default, JavaScript closes a statement at the end of a line. Due to this behavior, the two JavaScript code examples below are going to return an identical result:
function sampleFunction(a) {
var value = 10;
   return a * value;
}
JavaScript also allows breaking statements into two lines, which is why the third example is also going to have the same result:
function sampleFunction(a) {
varÂ
value = 10;
   return a * value;
}
Now, if the return
statement is broken in two lines like you can see in the example, the function will return undefined
:
function sampleFunction(a) {
varÂ
value = 10;
   returnÂ
a * value;
}
This happens because JavaScript interprets the code like this:
function sampleFunction(a) {
var
value = 10;
   return;
   a * value;
}
The system identifies an incomplete statement (var
) and tries to complete it by going on to the following line (value = 10;
). However, because the return
can be a complete statement when used on its own, JavaScript considers it to be completed and closes it, since there is nothing else on the line. This happens because closing a statement with a semicolon is not required in JavaScript.
Regardless, you should never break return
statements if you wish for your code to run smoothly.
Commas at the End of Definitions
As you separate the items in your array by commas, it's easy to leave one at the end, too, like in the example below.
numbers = [52, 452, 452, 1, 32, 45,];
If you do this, some JavaScript or JSON engines may fail or produce unexpected results. Therefore, make sure not to leave any symbols unattended:
numbers = [52, 452, 452, 1, 32, 45];
Same goes when defining a JavaScript object. The example below displays what you should never do:
user = {
firstName: "Joe";
lastName: "Johnson";
age: 32,
};
Memorize the correct way - it's not that hard:
user = {
firstName: "Joe",
lastName: "Johnson",
age: 32,
};
Other Issues
The variety of mistakes you can make is endless. The good thing is, you can learn from them and gain a better understanding of how your code works. If you identify and correct them, that is.
We will finish by describing a few more mistakes that occur often. Review the JavaScript examples carefully to get familiar with every issue. This will let you recognize and solve your own errors much more efficiently.
Arrays with Named Indexes
Even though many programming languages support arrays with name indexes, JavaScript is an exception. Here, arrays can only use numbered indexes, as shown in the example below:
var user = [];
user[0] = "Joe";
user[1] = "Johnson";
user[2] = 32;
var a = user.length;
var b = user[0];
However, objects in JavaScript can use named indexes.
Keep in mind that if you try to use a named index on an array, the array will be redefined to a standard object. After this redefinition, you will not be able to use array methods on this object, even if it used to be an array:
var user = [];
user["fName"] = "Joe";
user["lName"] = "Johnson";
user["age"] = 32;
var a = user.length;Â Â Â Â Â Â Â Â // user.length returns 0
var b = user[0];Â Â Â Â Â Â Â Â Â Â Â Â // user[0] returns undefined
Handling Floats
Each number in JavaScript is stored as a 64-bit floating point number (a float). Every programming language has difficulties with precise floating point values, and JavaScript is no exception:
Multiplying and dividing solves the problem:
Undefined vs. Null
In JavaScript, null
applies to objects, and undefined
to variables, methods, and properties. However, for an object to be null
, it has to be actually defined, else it is undefined
. To give you a real world example, null
would indicate an empty box, and undefined
would mean no box whatsoever.
In the example below, the if
statement checks whether the object is undefined
and null
:
if (sampleObject !== null && typeof sampleObject !== "undefined")
Finding out the difference might be hard when you have an empty object. For this reason, use typeof()
function as a simple test:
if (typeof sampleObject !== "undefined" && sampleObject !== null)
Block Level Scope
JavaScript does not generate a new scope with each new block of code. This is another exception in JavaScript, compared to other programming languages. A mistake that comes up in a lot of JavaScript for dummies tutorials is that beginners seem to think that this code is going to return undefined
:
for (var i = 0; i < n; i++) {
   // code code code
}
return i;
JavaScript Common Mistakes: Summary
- It is important in JavaScript to differentiate assignment
=
and comparison==
operators. - You should be aware of how addition and concatenation are executed.
- You should know how to properly break strings and what happens when you break a
return
statement. - You should know where to place semicolons and commas.