8 Common JavaScript Mistakes That You Should Avoid

8 Common JavaScript Mistakes That You Should Avoid

Amy J. Andrews

What are the mistakes almost every developer has made throughout his career?

Photo by Varvara Grabova on Unsplash

JavaScript is the most flexible language I ever learn in my career so far. Is flexibility a good thing though? Not really. This kind of flexibility tends to confuse us to some extent.

In my daily work, I often see the same mistakes are being made over and over again that I will list them out in the following for you to not fall into the same traps.

Let’s dive right in.

1. Block-level scoping

Have a look at the example below:

function justLog(inside) {
  if (inside) {
    var message = ‘this is a message’;
    console.log(‘Inside block:’, message);
  }
  
  console.log(‘Outside block:’, message);
}
justLog(true);

What result do you think will be printed on the screen?

The second console.log is logging the variable message that is outside the block that it’s defined. You may think the result will be:

Inside block: this is a message
error: Uncaught ReferenceError: message is not defined

But it’s not. Because of the ability of the var keyword, the correct result is:

Inside block: this is a message
Outside block: this is a message

So confusing, isn’t it?

I don’t use var keyword anymore. Instead, I use let. In my opinion, let makes more sense than var. And, you can avoid some common mistakes by using let.

2. Use “this” incorrectly

In JavaScript, the keyword this is confusing sometimes. When you use this without clearly understanding the context, it’s probably not the this you’re expecting.

Especially when you use this with a callback or a closure. Take a look:

var Game = {
  level: 1,
  start: function() {
    console.log(‘Start level ‘ + this.level);
  },
  finish: function() {
    setTimeout(function() {
      console.log(‘Finish level ‘ + this.level);
    }, 5);
  }
}
Game.start(); // Start level 1
Game.finish(); // Finish level undefined

We got undefined as the result of this.level after calling Game.finish(). Why? Because we’re using this in setTimeout function, which is in the window object’s context. And there’s no variable level in that context.

One of the solutions you can use is saving the reference to this in a variable as below:

Game.finish = function() {
  self = this;
  setTimeout(function() {
    console.log(‘Finish level ‘ + self.level);
  }, 5);
}

3. Don’t use strict mode

Using strict mode should be the rule of thumb. I don’t know why some developers don’t put this tiny, yet powerful statement at the beginning of the files.

‘use strict’ helps to remove silent errors.

‘use strict’ makes debugging easier.

‘use strict’ secures your code.

‘use strict’ prevents unexpected assigning.

Don’t forget to use it.

4. Create unexpected global variables

Either you’re a junior or a senior developer, you face memory leaks sometimes. And it’s a practical problem.

The common leak is when you define an unexpected global variable. For example:

function sayHello() {
  message = ‘Hello’;
  console.log(message);
}

The variable message is defined without the keyword let or var. Therefore, a variable message will be created inside the global object. In most cases, it’s the window object. As a result, an unexpected global variable is created and it’s not swept away by garbage collectors.

To deal with this problem, simply add ‘use strict’ at the beginning of every JavaScript file. It will prevent unexpected global variables.

5. Handle too many tasks in one function

There’re developers who like to put a lot of things in one single function. If you are one of them, stop it right now.

The real developer should break the long function into smaller ones and to the point. There are some advantages to writing such functions:

  • They are easier to maintain.
  • They are easier to read and understand.
  • Increase code reusability by moving common operations to separate functions.
  • It’s easier to debug a small block of code than a long complex one.

Keep in mind that if there’s more than one task executed in a function, consider dividing it up into smaller ones.

6. Equality

We have three types of equal operator in JavaScript: =, ==, ===. The first one is for assigning and the rest are for comparing.

JavaScript is a flexible language. In other languages, you can’t use the assigning operator ‘=’ with an if statement. In JavaScript, you can. And that’s when confusion takes place.

For example:

if (sum = 2) {
  // Do something
}

There’s no error syntax here. The result of the if above is always true. While you mean to compare the variable sum to 2, using the wrong operator will lead to unexpected results.

Although you can use ‘=’ in an if statement to do some hacks for your convenience, don’t. When it comes to comparison, always use ‘==’ or ‘===’.

7. Mismatch quotes and curly braces

When assigning a string to a variable, you type the opening quote and then the string value and somehow you forget the closing quote. The best way to avoid this mistake is to type the opening quote and the closing one at the same time and then put the value between them.

For example:

let message = ‘’;

The same implementation should be applied for curly braces:

function sayHello() {}

Just remember, if you are about to open an element, you need to close it as soon as possible.

8. undefined vs null

What can be the problem in the following code?


if (person !== null && person !== ‘undefined’) {
  // Do something
}

It’s that if the person object is not defined, an error will occur. You should change the order of the condition. Always check if an object is defined or not first before using it.

if (person !== ‘undefined’ && person !== null) {
  // Do something
}

Conclusion

JavaScript is a weird language. The common mistakes we make sometimes are weird too. Keep the above mistakes in mind to avoid further problems.

Of course, there is no way to avoid all of the mistakes in your career. As failures, the more mistakes you make the more experienced developer you become.

Hope you like this story!

And it’d be great if you mention the common mistakes you’ve made as a JavaScript developer and how you’ve dealt with them in the comment below.

Report Page