Most Common Mistakes in Javascript

Most Common Mistakes in Javascript

The most common mistakes in Javascript that you should avoid.

·

5 min read

Hey guys, in this article we'll discuss about the most common Javascript mistakes that developers make in theirs careers, What are the mistakes almost every Javascript developer and student has made throughout his learning and career?

JavaScript is a language that’s friendlier than many other programming languages in the world. However, it’s still very easy to make mistakes when writing JavaScript code through misunderstanding or overlooking stuff that we already know. By avoiding some of the mistakes below, we can make our lives easier by preventing bugs and typos in our code that bog us down with unexpected results.

1. 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);
}

2. Incorrect Use of Equality Operator

== and === both are used as Equality Operators

Interchange between them could lead to disastrous results.

3. Promise

This code seems async but it's not.

What's going on here?. The answer is easy, the promise cannot be resolved until the while loop is ends.

To solve this we can do this.

Now this is async because our code is inside Promise.resolve(). Try to run this now.

4. Assignment vs equality operators

In JavaScript a single equals sign (=) and double/triple equals sign (==/===) mean very different things so don't get them confused.

// Wrong

const text = "JavaScript";

if ((text = "JS")) {
  console.log(text);
} // output = JS
// Right

const text = "JavaScript";

if (text == "JS") {
  console.log(text);
} // no output

// OR

if (text === "JS") {
  console.log(text);
} // no output

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

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

7. Not using default values

Setting default values for dynamic or optional variables is good practice to prevent unexpected errors due to undefined values.

// Wrong

function addNumbers(a, b) {
  console.log(a + b);
}

addNumbers(); // NaN
// Right

function addNumbers(a = 0, b = 0) {
  console.log(a + b);
}

addNumbers(); // 0

addNumbers(5); // 5

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

9. Improper naming of variables

It's important to name variables as precisely and accurately as possible. This will prevent accidental duplication and make the code easier to read and understand.

// Wrong
const p = 600;
const d = 100;
const total = 500;
// Right
const price = 600;
const discount = 100;
const totalPrice = 500;

10. Misunderstanding scope

A Scope can be global or local and refers to the current context of code, which determines the accessibility of variables to JavaScript.

// Right

// Global scope variable
const firstName = "Dev";

function showMessage() {
  // Local scope variable
  const message = "Welcome back";

  console.log(`${message}, ${firstName}`);
}

showMessage(); // Welcome back, Dev

11. Merging Arrays using Addition Operator

  • Addition operator cannot be used to merge arrays
  • Instead of merging, the addition operator concatenates the last and first elements of arrays.
const arr1 = [1,2,3];
const arr2 = [4,5,6];
console.log(arr1 + arr2);

------ OUTPUT -------

1,2,34,5,6

Final word

Learning JavaScript (or any programming language) is not all about writing the code or learning the syntax.

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

Even if some developers seeing that JavaScript is a friendly language, it’s still very easy to make mistakes when writing JavaScript code. It’s easy to confuse undefined and null when we aren’t familiar with JavaScript. Because of the dynamic typing nature of JavaScript, operators like the + operator that can do multiple things can easily be converted to a type we don’t expect and produce the wrong result. Also, if statements can be complete on their own, then they shouldn’t be written in their own lines if we want both lines to be together.