Avoid common beginner mistakes in JavaScript

Even the best JavaScript programmers make mistakes. Here are some common mistakes that JavaScript programmers at all levels often make.

Mistake 0: Assuming JavaScript is relatively easy to learn.

Mistake 1:  Using global variable

Global variables are accessible from anywhere in your JavaScript, even in different files loaded on the same page. This is a bad idea, because it can be overwritten by anyone easily.

As a replacement, we can use namespace variables, object literals, modular pattern and so on. I will explain these techniques in a separate blog.

We often come across that developers use a variable without “var” keyword. Let us look at the following example. There is no “var” keyword before “i”. It obviously makes “i” as global.

for(i=0;i<length;i++) {

// do something


Mistake 2: Neglecting Semicolons

Every statement in JavaScript must end with a semicolon. But when we don’t put semicolons, compiler inserts semicolons for us. Hence it does not actually cause any issues.

But why do we rely on compiler to do it for us? Though there will be warnings in the file, whenever there is semicolon at the end of the line, we ignore them. Relying on the compiler is dangerous.

Mistake 3: Not using braces in if blocks

It is completely acceptable if we do not use braces for single line if blocks.

For example:

If (a < b) b – a;

But we often come across something like below.

If (a <  b)

b – a;

The above code does not cause any issues, but it makes difficult for anyone to read.

Sometimes we even see cases like below.

If (a <  b)

b – a;

c + d;

Doesn’t it make hard for us to read? In these cases, it is better to use braces, such that it makes easier to read.

Mistake 4: Not initializing the variable

Let us consider the following example.

var a;

if (c < d)


 a = “mango”;


If (a !== “mango”) {

  // do something


 It throws warnings at the line “If (a !== “mango”) {“. It says “the local variable may not have been initialized”. In such cases, we should initialize the variable. But we tend to ignore, because it is just a warning.

JavaScript is a mature, ubiquitous, but widely misused language. Eliminate these silly mistakes and your work will be very much easier and more productive.