10 common JavaScript errors and how to avoid them
Kazim Kayhan
Software Engineer | Frontend Developer | 2k+ LinkedIn | React.js, Next.js, TypeScript | Created UX-friendly websites | Passionate about interactive UI/UX.
JavaScript is one of the most popular and widely used programming languages in the world. It powers dynamic and interactive web pages, mobile applications, server-side applications, and more. However, JavaScript is also a language that can be tricky to master and prone to errors. In this blog post, we will look at 10 common JavaScript errors and how to avoid them.
This error occurs when the JavaScript interpreter encounters a token (a symbol or a word) that it does not expect or understand in a certain context. For example
let name = "Kazim
console.log(name);
The code above will throw a SyntaxError because there is a missing quotation mark at the end of the string “Kazim”. To fix this error, we need to add the missing quotation mark:
let name = “Kazim”;
console.log(name);
To avoid this error, we should always check our syntax carefully and use a code editor that highlights syntax errors.
2. ReferenceError: Variable is not defined
This error occurs when we try to access a variable that has not been declared or initialized. For example:
console.log(x);
let x = 10;
The code above will throw a ReferenceError because we are trying to use x before it is declared with var. To fix this error, we need to declare x before using it:
let x = 10;
console.log(x);
To avoid this error, we should always declare our variables with var, let, or const before using them.
3. TypeError: Cannot read property of undefined (or null)
This error occurs when we try to access a property or a method of an object that is undefined or null. For example:
const person = {
name: "Kayhan",
age: 25
};
console.log(person.job.title);
The code above will throw a TypeError because person.job is undefined and we cannot read its title property. To fix this error, we need to check if person.job exists before accessing its title property:
const person = {
name: "Kayhan",
age: 25
};
if (person.job) {
console.log(person.job.title);
}
To avoid this error, we should always check if an object or its property exists before accessing it.
4. RangeError: Invalid array length
This error occurs when we try to create an array with an invalid length value. For example:
let arr = new Array(-1);
The code above will throw a RangeError because -1 is not a valid array length value. To fix this error, we need to use a positive integer value for the array length:
let arr = new Array(10);
To avoid this error, we should always use valid values for the array length.
5. URIError: Malformed URI
This error occurs when we try to encode or decode a URI (Uniform Resource Identifier) with an invalid format. For example:
decodeURI("%");
The code above will throw a URIError because “%” is not a valid URI component. To fix this error, we need to use a valid URI component:
decodeURI("%20");
To avoid this error, we should always use valid URI components for encoding or decoding URIs.
6. Uncaught exception
This error occurs when an exception (an unexpected event that disrupts the normal flow of execution) is thrown but not caught by any catch block in the code. For example:
领英推荐
function divide(a,b) {
if (b === 0) {
throw new Error("Cannot divide by zero");
}
return a / b;
}
console.log(divide(10,0));
The code above will throw an uncaught exception because there is no catch block to handle the Error object thrown by divide(). To fix this error, we need to add a catch block after the try block that calls divide():
function divide(a,b) {
if (b === 0) {
throw new Error("Cannot divide by zero");
}
return a / b;
}
try {
console.log(divide(10, 0)); // This will trigger an error
} catch (error) {
console.error(error.message); // "Cannot divide by zero"
}
try {
console.log(divide(10, 2)); // This will not trigger an error
} catch (error) {
console.error(error.message); // This will not execute
}
To avoid this error, make sure to use `try…catch` blocks wherever appropriate and handle different types of exceptions accordingly.
7. Stack Overflow: Maximum call stack size exceeded
Stack Overflow is a type of error that occurs when a computer program runs out of memory allocated for its call stack. A call stack is a data structure that keeps track of the execution of a program by storing information about the functions being executed. When a function is called, its information is added to the top of the call stack, and when the function is completed, its information is removed from the top of the stack.
The “Maximum call stack size exceeded” error is a common example of a stack overflow error in JavaScript. This error occurs when a function calls itself too many times, creating an infinite loop that fills up the call stack and causes it to overflow. For instance:’s an example:
function countdown(n) {
if (n <= 0) {
return;
}
console.log(n);
countdown(n - 1);
}
countdown(5);
In this example, the countdown function is recursively called with decreasing values of n. However, if we call countdown with a large value of n, such as countdown(100000), the call stack will eventually overflow and we will see the "Maximum call stack size exceeded" error.
To avoid stack overflow errors, it’s important to make sure that recursive functions have a base case that eventually terminates the recursion and to avoid calling functions within a loop that could potentially create an infinite loop.
8. Memory leak
A memory leak is a type of error in JavaScript that occurs when a program uses more memory than it should and does not release the memory when it is no longer needed. Over time, this can cause the program to slow down or crash.
Example of a memory leak:
let elements = [];
function addElement() {
let element = document.createElement('div');
elements.push(element);
document.body.appendChild(element);
}
setInterval(addElement, 1000);
In this example, the addElement function is called every second using the setInterval method. This function creates a new div element, adds it to the elements array, and appends it to the document.body element.
Over time, the elements array will continue to grow as new elements are added, but there is no code to remove old elements from the array. This means that the program will continue to use more and more memory, eventually causing a memory leak.
To fix this memory leak, we can modify the addElement function to remove old elements from the array:
let elements = [];
function addElement() {
let element = document.createElement('div');
elements.push(element);
document.body.appendChild(element);
if (elements.length > 10) {
let oldElement = elements.shift();
document.body.removeChild(oldElement);
}
}
setInterval(addElement, 1000);
In this modified version of addElement, we check the length of the elements array and remove the first element from the array and from the document.body element if there are more than 10 elements in the array. This ensures that the program does not use more memory than it needs, and avoids a memory leak.
To avoid memory leaks in JavaScript, it’s important to properly manage event handlers, avoid global variables, release memory from unused objects, be careful with closures, and use a memory profiler tool to identify and fix memory leaks.
9?. Promise rejection error
A Promise rejection error occurs in JavaScript when a Promise object is rejected, which means that it has failed to fulfill its intended purpose. Promises are a way to handle asynchronous operations in JavaScript, allowing the program to continue executing while waiting for a task to complete.
An example of a Promise rejection error:
let promise = new Promise((resolve, reject) => {
setTimeout(() => {
reject('Error: Promise was rejected');
}, 1000);
});
promise.then(result => {
console.log(result);
}).catch(error => {
console.log(error);
});
In this example, we create a new Promise object that waits for one second before rejecting it with an error message. We then attach a then and catch method to the Promise object, which will be called depending on whether the Promise is resolved or rejected.
Since the Promise in this example is rejected, the catch method will be called and the error message will be logged into the console.
To avoid Promise rejection errors, it’s important to handle any potential errors in the Promise code and use the catch method to handle any rejected Promises.
10?. The async/await errors
These errors occur when you use async/await syntax (a way of writing asynchronous code in a synchronous-like manner) but do not handle possible errors correctly. To avoid async/await errors, it is important to handle possible errors correctly. Here are some tips:
An example of how to use async/await with proper error handling:
async function fetchData() {
try {
const response = await fetch('https://example.com/data.json');
const data = await response.json();
return data;
} catch (error) {
console.error('An error occurred:', error);
// Return a rejected Promise so the caller can handle the error appropriately
return Promise.reject(error);
}
}
// Call the function and handle any possible errors
fetchData()
.then(data => {
console.log('Data received:', data);
})
.catch(error => {
console.error('An error occurred:', error);
});
In conclusion, I wrote this article to help JavaScript developers avoid common mistakes that can lead to bugs and performance issues in their code. As someone who has experienced these issues firsthand, I understand how frustrating they can be. I hope this article serves as a helpful guide for your JavaScript development endeavors.
Data Engineer #aws #snowflake #pyspark #dataengineer #analyticalengineer #dbt #glue #datamodeling -> For any developer Mock Interviews DM ( I don't Charge as a #mentor )
2 年reach++