In JavaScript, errors are inevitable parts of programming. They act as helpful messages that let us know when something has gone wrong. JavaScript provides a built-in Error
object that contains valuable information about the error. Understanding the types of errors and their causes is crucial for debugging and writing robust code.
Let’s explore some of the most common types of errors in JavaScript: Syntax Error, Reference Error, and Type Error.
1. Syntax Error
A Syntax Error occurs when we write code that does not follow the correct syntax rules.
Example:
console.log('hello world'
Reason: There’s a missing closing parenthesis. The JavaScript engine cannot parse this code.
- Reference Error A Reference Error occurs when we try to access a variable or function that has not been defined.
Example:
console.log(a);
Reason: The variable a is not declared.
- Type Error A Type Error occurs when a value is used in an unexpected way or is of an unexpected type.
Here are a few common reasons why Type Errors occur:
- Calling a non-function If we try to invoke a variable as a function, but it is not actually a function, a Type Error will be thrown.
Example:
const obj = {};
obj();
// TypeError: obj is not a function
- Accessing properties of undefined or null This error occurs when we try to access a property of a variable that is undefined or null.
Example:
let myVar;
console.log(myVar.name);
// TypeError: Cannot read property 'name' of undefined
- Modifying a constant variable A Type Error also occurs when we try to change a constant variable’s value.
Example:
const x = 5;
x = 10;
// TypeError: Assignment to constant variable
Top comments (0)