Common mistakes in JavaScript

Ranjul Arumadi
Last Updated: May 13, 2022

Introduction

While working with Javascript, you are bound to make mistakes. Sometimes you might realize them, or at times, they might not come to your attention. There might also be practices that you feel are sufficient while writing code but, in reality, may not be. 

 

If you are planning a career in JS, why not check out some Javascript Interview Questions? Reading through these questions will give you an idea of the important concepts you should know while working with JS.

 

This blog will talk about Common mistakes in JavaScript that you might be making as a Javascript developer.

Some common mistakes in JavaScript

If you are working with JavaScript, there is always a chance that you will make mistakes. Mistakes can come from misplacing semicolons to issues working with floats etc.

 

By going through this blog, you have an idea of the common mistakes in JavaScript that you might make, thereby reducing the chances of making them.

 

Misplacing Semicolons

Semicolons are used in many programming languages to indicate the termination of a statement. Javascript also makes use of semicolons to let it understand that a statement has terminated. Even though it is not a strict rule to use them, it is good to make your code better.

 

The issue of working with semicolons in Javascript is that sometimes you might misplace them at the wrong places. This is one of the common mistakes in JavaScript. Let us see a situation where this issue will come up.

<!DOCTYPE html>
<html>
<body>
<h2>Coding Ninjas!</h2>
<p id="test"></p>
<script>
let x = 5;
// Semicolon misplaced after while condition closing parenthesis
while (x > 5);
{
document.getElementById("test").innerHTML = "Hello Ninja!";
}
</script>
</body>
</html>

 

Output:

Coding Ninjas!
Hello Ninja!

 

In the above example, "Hello Ninja!" isn't expected to come in the output as clearly x is not greater than 5. The unexpected result is because the semicolon was put after the closing parenthesis of the while loop condition. By placing the semicolon there, the body of the loop gets separated from the condition. So, now the body will get executed no matter what the condition is.

Assignment operator instead of a comparison operator

Assignment operators (=) are used to assign values to a variable. On the other hand, comparison operators are used for checking the equality or difference between variables or values. In javascript, we have a different comparison operator (===) and the general comparison operator (==) that we see in many other programming languages like C, C++, etc. 

 

The == operator is used for comparison irrespective of their data types. In contrast, the === operator is used to compare variables along with performing a strict type check. Sometimes you might use = rather than == or ===, which can lead to unexpected results. Let us examine a situation where this issue will come.

<!DOCTYPE html>
<html>
<body>
<p>Coding Ninjas!</p>
<p></p>
<p id="test"></p>
<script>
let x = 7;
// The unexpected result would not come up if we had used == in the condition rather than =
if(x = 6){
document.getElementById("test").innerHTML = "Hello Ninja!";
}
</script>
</body>
</html>

 

Output:

Coding Ninjas!
Hello Ninja!

 

Corrected code:

<!DOCTYPE html>
<html>
<body>
<p>Coding Ninjas!</p>
<p></p>
<p id="test"></p>
<script>
let x = 7;
// The issue was resolved by replacing = with ==
if(x == 6){
document.getElementById("test").innerHTML = "Hello Ninja!";
}
</script>
</body>
</html>

 

Output:

Coding Ninjas!

Loose comparison

This relates to the fact that Javascript has both == and the ===. The == operator is used for comparison irrespective of their data types, whereas the === operator is used to compare variables and perform a strict type check. Sometimes you might use = rather than == or === which can lead to unexpected results.

 

Code:

<!DOCTYPE html>
<html>
<body>
<p>Coding Ninjas!</p>
<p id="test"></p>
<script>
let x = 10;
let y = "10";

// Unexpected result because of using == than ===
if(x==y){
document.getElementById("test").innerHTML = "Hey!";
}
</script>
</body>
</html>

 

Output:

Coding Ninjas!
Hey!

 

Corrected code:

<!DOCTYPE html>
<html>
<body>
<p>Coding Ninjas!</p>
<p id="test"></p>
<script>
let x = 10;
let y = "10";

// Used === over == giving us correct output
if(x===y){
document.getElementById("test").innerHTML = "hey!";
}
</script>
</body>
</html>

 

Output:

Coding Ninjas!

Note that switch statements use strict comparison.

Addition & Concatenation

Addition means adding two numeric values. Concatenation, on the other hand, is adding strings. Adding as well as concatenation can be performed using the same + operator.

 

Adding two numeric values:

let x = 9;
x = 9 + 1;       // Now x value is 10

Concatenating to strings:

let x = "1 ";
let y = "Ninjas";
Let z = x + y // Now z will have the value "1 Ninjas"

Adding string and numeric value:

let x = "1 ";
let y = 1;
let z = x + y; // Now z will have the value "1 1"

Working with floats

The numbers in JavaScript are stored as 64-bits Floating point numbers (Floats). We might face difficulties while working with precise floating-point values.

 

Code:

let x = 0.2;
let y = 0.1;
let z = x + y            // the result in z will not be 0.3 but 0.30000000000000004 

 

One way to quickly get around this issue would be to multiply and divide by 10. Let me show you the code.

 

Code:

let x = 0.2;
let y = 0.1;
let z = (x*10 + y*10)/10; // Now z will have the value 0.3

Breaking a JavaScript String

Javascript gives you the freedom to break a single statement into two lines. However, you cannot break them in the middle of a string. This will create errors. If you want to break statements in the middle of a string you can use \(backslash).

 

Code:

let x =
"Hello Ninja!";         // This is allowed

let x = "Hello
Ninja!";                   // This is not allowed
/*Using backslash to get around this issue*/
let x = "Hello \
Ninja!";                  // This is allowed

Accessing Arrays with Named Indexes

Many programming languages like C, C++ only allow numeric index values. Javascript is also one such language. In Javascript, if non-numeric values are array indices, we might get incorrect or undefined results.

 

Code:

/* We get perfectly expected outputs using numeric indices for arrays */
const languages = [];
languages[0] = "C";
languages[1] = "C++";
languages.length;       // languages .length will return 2
languages[0];           // languages [0] will return "C"
/* Using non-numeric indices */
const languages = [];
languages["language_1"] = "C";
languages["language_2"] = "C++";
languages.length;       // languages .length will return 0 
language [0];           // languages [0] will return undefined

 

As you can see, using non-numeric indices gives us wrong and undefined results.

Ending Definitions with a Comma

Ending definitions may not seem as logical, but Javascript permits to end arrays with a comma. In this situation, JavaScript simply ignores the last comma. Since ECMAScript5, JavaScript has also been permitted to end objects with commas as well. However, note that JSON does not allow trailing commas.

 

Code:

Numbers = [10, 20, 14, 55, 245, 120,];  // This is legal
person = {firstName:"Ninja", profession:"Coder",} // This is also allowed since ECMAScript5

Undefined is Not Null

Javascript can get you confused between undefined and null. Note that they are not the same. You can use the typeof operator to clear your doubts.

Source: https://twitter.com/ddprrt/status/1074955395528040448

 

Code:

// program to check if a variable is undefined or null
function checkTheVariable(variable) {
   if( typeof variable === 'undefined' || variable === null ) {
       console.log('Undefined or null');
   }
   else {
     console.log('Neither undefined nor null');
   }
}
let testVariable;
checkTheVariable(77);
checkTheVariable('Ninja!');
checkTheVariable(null);
checkTheVariable(testVariable);

 

Output:

Neither undefined nor null
Neither undefined nor null
Undefined or null
Undefined or null

No block-level scope

This is an important concept that must be noted, especially if JavaScript is not your first language and you are coming from other programming languages like C, Java, etc.

 

Let us look at a sample java code.

 

Code:

public class Block_Scope
{
   public static void main(String args[])
   {
       {
           // The variable x has scope within the curly braces only
           int x = 747;
           System.out.println(x);  // OUTPUT1
       }
       
     // System.out.println(x);  // Uncommenting this will generate error as the variable x has scope only with the curly braces where it was defined
   }

}

 

Output:

747 

 

This is not the case with Javascript.

 

Let us look into a sample code.

 

Code:

for (var j = 0; j < 10; j++) {
 j = j + 1;
}
console.log ( j );

 

Output:

10

 

In other languages, the variable j is destroyed after the loop is finished.

Referencing code before it's loaded

JavaScript loads and runs the code in the order in which it appears in the document. Suppose if the HTML head section has some script defined which is trying to access the HTML elements, then errors may get thrown.

 

Let us see an example of this.

 

Code:

<html>
 <head>
     <script> document.getElementById('testDiv').innerHTML = 'Hello Ninja!; </script>
 </head>
 <body>
     <div id "testDiv"></div>
 </body>
</html>

 

There are two ways to get around this problem. One way would be to put the script code at the end of the file. The other method would make use of an attribute called defer while loading the JavaScript file. Defer is used to tell the browser to only execute the scripts after completely parsing the HTML file.

 

Code:

<html>
 <head>
     <script src="myScript.js" defer> </script>
 </head>
 <body>
     <div id = 'testDiv'></div>
 </body>
</html>

Frequently Asked Questions

  1. What are some of the common mistakes in JavaScript a developer usually makes?
    Common JavaScript mistakes include missing semicolons, confusion between assignment and comparison operators, loose comparisons, confusion between addition and concatenation, working with floats, etc.
     
  2. How can I reduce programming mistakes?
    Slowing down while coding can help you think better. Choosing IDE's can help as they will show any errors in real-time as you type. Testing the code helps in identifying the errors and mistakes that you might have made.

Key Takeaways

Javascript is one of the most popular programming languages, and working with it can be fun. However, just like working with any programming language, there will be many common mistakes in JavaScript that you might make. Mistakes from misplacing semicolons to issues working with floats are common mistakes in JavaScript that developers make. 

 

By going through this blog, you have created yourself aware of the common mistakes in JavaScript that you might make, thereby reducing the chances of making them.

 

If you enjoyed reading this article about the Common mistakes in JavaScript, check out Learn starting with Javascript and 20 Projects With JavaScript Code Examples.

Was this article helpful ?
0 upvotes

Comments

No comments yet

Be the first to share what you think