1) Using uninitialized variables
One of the most common mistakes is using an uninitialized variable. The problem is that the value of an uninitialized variable can be anything, and if we assume it has one value when it actually has another value, our code will probably break.
The best way to get around this issue is by initializing all your variables before you use them. A simple way of doing this is by assigning a value at the same time you declare your variable:
var x = 5;
2) Declaring variables in the global scope
Another common mistake is declaring variables in the global scope, instead of inside functions or blocks like if statements and loops.
If you do this, then your program may unintentionally overwrite data stored in global variables because they share a single namespace. This results in errors that are very hard to debug because they may not appear immediately. For example:
var x = 1; // 1st scenario var x = 1
Many of the errors that you’ll encounter can be avoided with better planning and more careful code review. Others are just common errors that all programmers make when they start working with a new language.
In this article I’m going to explain some common mistakes and pitfalls, and why they happen. I’ll also show how to fix them, and what tools can help you prevent them in the future.
In this article I would like to give you some tips on how to avoid these mistakes in your code.
1. Unused variables and functions
2. Wrong usage of scope
3. Overusing global variables
This mistake is similar to not using scope properly but even worse because you’re affecting other parts of your code base. To avoid this mistake try not to use global variables unless you really have to (like libraries such
1) Not using ===
// Using == will return true
1 == “1” // true
// Using === will return false since 1 and “1” are different types
1 === “1” // false
2) Omitting var
Variables declared with var are scoped to the function they are declared in or global if declared outside a function. Variables not declared with var are always global (assuming they’re not caught by a catch clause or
These are not in any particular order, as they vary in severity depending on what you’re doing. Also, there is a lot of code snippets that are written inline, so please excuse me if they’re a little sloppy.
1. Using == instead of ===