31.5 C
Pakistan
Saturday, July 27, 2024

10 Typical JavaScript Errors and Solutions

The foundation of contemporary web development, JavaScript, enables programmers to create dynamic and interactive websites.

But there are obstacles in the way of learning this language. Common JavaScript errors are a common source of frustration for even seasoned developers. But one can avoid them. Now let’s explore some of the typical mistakes you might make.

1. Undefined is Not a Function

Consider that you are attempting to invoke a function that is not yet defined. This frequently occurs when a function is declared in the code after it has been called. Examine the example that follows.

// Bad practice
calculateTotal(); // Error: calculateTotal is not a function
// Function declaration appears later in the code
const calculateTotal = () => {
  // code here
};

There will be an error if calculateTotal() is called before the function is declared because calculateTotal is not defined at that point in the code. It hasn’t been tackled by the JavaScript engine yet.

Always make sure to call functions after they have been correctly defined to avoid running into this error, as shown here:

// Function declaration appears before the function call
const calculateTotal = () => {
  // code here
};

calculateTotal(); // No error, function is defined before the call

2. Typos and Case Sensitivity

Because JavaScript is case-sensitive, two variables, name and Name, would exist in memory that are completely different from one another.

Errors that are difficult to detect can result from typos. Make sure your function calls and variable names are consistent across your code by paying special attention to them.

// Bad practice
Console.log("Hello, World!");

// Good practice
console.log("Hello, World!");

Not much to say here, except to warn you that JavaScript is case-sensitive.

3. Parentheses and Brackets Mismatch

This is yet another thing to be annoyed about. Errors (and headaches!) frequently result from mismatched parentheses and brackets. Make sure the opening and closing brackets line up properly by checking them twice.

// Bad practice
if (condition {
    // code here
}

// Good practice
if (condition) {
    // code here
}

4. NaN (Not a Number)

Exercise caution when performing mathematical operations. When a JavaScript operation fails, it returns ‘NaN’. Verify your inputs before running computations to prevent this.

// Bad practice
const result = parseInt("abc123");

// Good practice
const input = "abc123";
const result = parseInt(input);
if (!isNaN(result)) {
  console.log("Hello");
}

5. Semicolon Insertion

Semicolons are automatically inserted by JavaScript, but it’s best not to depend on this behavior. Adding semicolons explicitly helps avoid unforeseen mistakes, particularly in complex code.

// Bad practice
let a = 10
let b = 20

// Good practice
let a = 10;
let b = 20;

Although many people disregard semicolons altogether, we find that to be extremely offensive! You can, however, omit semicolons if you are aware of the rules surrounding them (don’t do it, though; I’m kidding).

6. Asynchronous Callbacks

JavaScript’s asynchronous operations are very basic; they let programs run continuously, resulting in a seamless user experience.

But working with asynchronous code, particularly when using callbacks, can be challenging and frequently result in mistakes.

Let’s examine this frequent roadblock in more detail and discover the best way to deal with asynchronous callbacks.

Imagine a situation where you would like to retrieve information from an API and take actions based on it. Because of the nature of APIs, this operation is asynchronous, which means that the program doesn’t stop to wait for it to finish; instead, it takes time to complete. Rather, JavaScript proceeds with executing the subsequent code lines.

// Bad practice
const fetchData = () => {
  let data;
  fetch("https://api.example.com/data")
    .then((response) => response.json())
    .then((result) => {
      data = result;
    });
  return data; // Incorrect: This returns undefined as fetch hasn't completed yet
}

// Good practice
const fetchData = callback => {
  fetch("https://api.example.com/data")
    .then((response) => response.json())
    .then((result) => {
      callback(result); // Correct: Pass the data to the callback function
    });
}

fetchData(data => {
  console.log(data); // Process data inside the callback function
});

The fetchData function in the bad practice example tries to return data that was retrieved from an API. But because fetch is asynchronous, the function returns before the data is ready, which results in undefined.

The usage of callbacks is illustrated in the good practice example. The function takes a callback parameter and attempts to return the asynchronous result via it instead of directly. The callback function receives the fetched data and uses it for additional processing. This guarantees that operations reliant on the retrieved data only take place following the completion of the asynchronous task.

Additionally, async/await, a potent feature that helps handle asynchronous code elegantly, is introduced by modern JavaScript. Here’s how to use async/await to rewrite the fetchData function:

// Using async/await
async function fetchData() {
  try {
    let response = await fetch("https://api.example.com/data");
    let data = await response.json();
    return data;
  } catch (error) {
    console.error("Error fetching data:", error);
  }
}

fetchData().then((data) => {
  console.log(data); // Process data inside the promise resolution
});

The asynchronous code is made simpler and appears synchronous while maintaining its non-blocking nature thanks to async/await.

When the operation is successful, the fetchData function retrieves the data, waits for the response, processes it, and then returns the data.

You can handle asynchronous operations efficiently, avoid common errors, and make sure your JavaScript code works flawlessly in real-world scenarios by learning about asynchronous callbacks and utilizing contemporary JavaScript features.

7. Uncaught TypeErrors

Mismatched data types are frequently the cause of type errors. Verify the types of your variables before doing any operations on them to prevent them.

// Bad practice
const number = "123";
const sum = number + 5;

console.log(sum); // '1235'

// Good practice
const number = "123";
const parsedNumber = parseInt(number);
if (!isNaN(parsedNumber)) {
  let sum = parsedNumber + 5;
}

8. Infinite Loops

Your application may crash due to infinite loops. In order to keep the loop from continuing indefinitely, always make sure there is a condition that permits it to end.

// Bad practice
while (true) {
  // code here
}

// Good practice
let condition = true;
while (condition) {
  // code here
}

9. Overwriting Variables

Inadvertent overwriting of variables can result in strange behavior. Keep in mind variable scopes and refrain from accidentally using the same variable names twice.

// Bad practice
const calculateTotal = (price) => {
  let total = 0;
  for (let i = 0; i < price.length; i++) {
    let total = total + price[i];
  }
  return total;
};

// Good practice
const calculateTotal = (price) => {
  let total = 0;
  for (let i = 0; i < price.length; i++) {
    total = total + price[i];
  }
  return total;
};

10. Ignoring Browser Compatibility

JavaScript code is interpreted differently by different browsers. Always think about cross-browser compatibility and test your code across a variety of browsers to prevent unforeseen problems on particular systems.

An informative website exists, Can I Use

to verify if the browser is compatible. Keep it bookmarked and use it frequently!

In summary

You can write reliable and error-free code by being aware of and avoiding these typical JavaScript mistakes. In the always changing world of web development, your best friends are a constant state of learning and meticulous attention to detail.

With patience and practice, these mistakes will soon become minor roadblocks on your journey to becoming a proficient coder. Have fun coding!

Related Articles

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Latest Articles