DEV Community

Cover image for 10 Common Mistakes to Avoid While Writing JavaScript Code
Dhanush N
Dhanush N

Posted on • Updated on • Originally published at dhanushnehru.hashnode.dev

10 Common Mistakes to Avoid While Writing JavaScript Code

JavaScript is one of the most popular programming languages in use today, thanks to its versatility and ease of use. However, even experienced developers can make mistakes while coding in JavaScript, which can lead to bugs and errors in their code. In this blog post, we will discuss the 10 most common mistakes in JavaScript and how to avoid them.

  • Forgetting to declare variables with "var," "let," or "const": One of the most common mistakes in JavaScript is forgetting to declare variables using "var," "let," or "const." If you don't declare a variable, JavaScript will create a global variable, which can lead to unexpected behavior and bugs.
// Example of not declaring a variable:
myVariable = "Hello, world!"; // This will create a global variable
console.log(myVariable); // "Hello, world!"

// Correct way to declare a variable:
let myVariable = "Hello, world!";
console.log(myVariable); // "Hello, world!"
Enter fullscreen mode Exit fullscreen mode
  • Using "==" instead of "===": JavaScript has two types of equality operators: "==" and "==="; the latter is known as strict equality. Using "==" can lead to unexpected behavior because it performs type coercion, which means that JavaScript will try to convert the types of the two operands to make them equal. It's generally better to use "===" for strict equality checks.
// Example of using "==":
console.log(1 == "1"); // true - type coercion occurs

// Example of using "===":
console.log(1 === "1"); // false - strict equality check
Enter fullscreen mode Exit fullscreen mode
  • Not understanding hoisting: Hoisting is a JavaScript behavior where variable and function declarations are moved to the top of their respective scopes. This means that you can use a variable or function before it's declared, which can lead to unexpected behavior if you're not aware of hoisting.
// Example of hoisting:
myFunction(); // This works even though the function is defined later

function myFunction() {
  console.log("Hello, world!");
}
Enter fullscreen mode Exit fullscreen mode
  • Ignoring semicolons: JavaScript is a semicolon-sensitive language, which means that you should end statements with semicolons. JavaScript uses automatic semicolon insertion (ASI) to insert semicolons where it thinks they are necessary. but this can be unreliable and lead to hard-to-debug issues. While JavaScript can usually infer where semicolons should be inserted, it's a good practice to add them explicitly to avoid unexpected errors. Some developers choose to omit semicolons as a personal preference or to reduce code clutter, but it is generally recommended to use semicolons to avoid potential issues.
// Example of not using semicolons:
let a = 1
let b = 2

// Correct way to use semicolons:
let a = 1;
let b = 2;
Enter fullscreen mode Exit fullscreen mode
  • Using "var" instead of "let" or "const": "Var" is an older variable declaration keyword in JavaScript that has been replaced by "let" and "const." Using "var" can lead to unexpected behavior because it doesn't have block-level scoping like "let" and "const."
// Example of using "var":
var myVariable = "Hello, world!";

// Better to use "let" or "const":
let myVariable = "Hello, world!";
const myConstant = "Hello, world!";
Enter fullscreen mode Exit fullscreen mode
  • Overusing global variables: Using global variables excessively can lead to naming collisions and unexpected behavior. It's generally better to use local variables and functions to minimize the impact of any changes on the global scope.
// Example of overusing global variables:
let x = 1;
function myFunction() {
  x = 2;
}
myFunction();
console.log(x); // 2 - global variable was changed by the function

// Better to use local variables:
function myFunction() {
  let x = 2;
  console.log(x); // 2 - local variable
}
myFunction();
Enter fullscreen mode Exit fullscreen mode
  • Not handling errors properly can lead to unexpected behavior and even crashes. It's a good practice to include try-catch blocks to handle errors and provide informative error messages.
// Example of not handling errors properly:
try {
  myFunction();
} catch (error) {
  console.error(error);
}

// Better to provide informative error messages:
try {
  myFunction();
} catch (error) {
  console.error("Error in myFunction:", error);
}
Enter fullscreen mode Exit fullscreen mode
  • Not using strict mode: JavaScript's strict mode is a way to opt into a stricter set of rules and best practices. Enabling a strict mode can help catch common errors and enforce better coding practices.
// Example of not using strict mode:
function myFunction() {
  myVariable = "Hello, world!"; // This will throw a ReferenceError
}

// Better to use strict mode to catch errors:
function myFunction() {
  "use strict";
  let myVariable = "Hello, world!";
}
Enter fullscreen mode Exit fullscreen mode
  • Using synchronous code where asynchronous code is necessary: JavaScript is designed to be asynchronous, which means that you should use asynchronous code when waiting for I/O operations or other time-consuming tasks. Using synchronous code in these situations can lead to slow performance and even crashes.
// Example of using synchronous code for an I/O operation:
let data = fs.readFileSync("file.txt"); // This will block the event loop

// Better to use asynchronous code:
fs.readFile("file.txt", (err, data) => {
  if (err) console.error(err);
  console.log(data);
});
Enter fullscreen mode Exit fullscreen mode
  • Not testing code thoroughly: Finally, not testing code thoroughly can lead to bugs and unexpected behavior. It's a good practice to write unit tests and integration tests to ensure that your code is working as expected and to catch any issues before they become a problem in production.
// Example of not testing code thoroughly:
function add(a, b) {
  return a + b;
}

console.log(add(1, 2)); // 3
console.log(add(1, "2")); // "12" - unexpected behavior

// Better to write tests to catch issues:
function add(a, b) {
  return a + b;
}

test("addition", () => {
  expect(add(1, 2)).toBe(3);
  expect(add(1, "2")).toBeNaN();
});
Enter fullscreen mode Exit fullscreen mode

In conclusion, JavaScript is a powerful and versatile language, but it's important to be aware of its potential pitfalls and common mistakes. By following best practices, testing thoroughly, and avoiding these common mistakes, you can write more reliable and bug-free code

Thank you so much if you have read it so far !!!

If you found this post helpful, don't forget to follow me on Twitter, Instagram, Github and subscribe to my YouTube channel ❀️

Oldest comments (4)

Collapse
 
idleman profile image
idleman • Edited

The absolute most common mistake in JavaScript is to declare a variable as "let". Sure, its valid cases but for 95% of the time should a variable be declared as "const". It ease reasoning, decrease bugs and make the variable easy to track. If the variable need to be modified in a loop, use the "Array#reduce" function. Makes the code most times more readable than the alternatives.

Very few new projects use "var" these days.

Collapse
 
dhanushnehru profile image
Dhanush N

Yeah, nowdays in projects we mostly use "let" & "const"

And mostly I have used "let" when we have to do a query operation from a database & store it in a variable & modify the contents in that variable and store it in the same variable and in much lesser cases.

Only in legacy code I have seen the usage of "var"

Collapse
 
eerk profile image
eerk

I always struggle a bit with the idea of writing tests, can't the test code itself contain a bug or unexpected behaviour? Do we need to write a test, to test the test? One solution for this can be typescript, which automatically checks if addNumber(a,b) receives two numbers and returns one number.

Collapse
 
jonrandy profile image
Jon Randy πŸŽ–οΈ

Don't worry about it. I've been a professional developer for 27 years, and have very rarely used any automated testing. It's not necessary, and not using it encourages a better understanding of the code you are working with.