Table of contents
No headings in the article.
What are TypeError and ReferenceError in JavaScript?
TypeError and ReferenceError are two common errors that can occur when working with JavaScript code. These errors occur when a program attempts to perform an operation on a value that is not of the expected type or when the program tries to access a variable or object that does not exist.
Let's take a closer look at each of these errors and how to identify and resolve them.
TypeError in JavaScript :
A TypeError occurs when a program attempts to perform an operation on a value that is not of the expected type. This can happen when passing arguments to a function, accessing properties or methods of an object, or attempting to perform mathematical operations on non-numeric values.
Here's an example of a TypeError in JavaScript:
In this example, we're attempting to call the trim()
method on a number num
, which is not allowed since trim()
is a method available only on strings.
To fix this TypeError, we need to make sure that we're calling the appropriate methods on the right data types. In this case, we need to convert num
to a string before calling the trim()
method on it. We can do this using the toString()
method like this:
Now the toString()
method will convert num
to a string and we can call the trim()
method on it without any errors.
ReferenceError in JavaScript
A ReferenceError occurs when a program attempts to access a variable or object that does not exist. This can happen when a variable is misspelled or when an object is not initialized before it is used.
Here's an example of a ReferenceError in JavaScript:
In this example, the myFunc
function tries to return the value of a variable c
, but c
has not been defined anywhere in the function or its scope. This results in a ReferenceError being thrown.
To fix this error, you need to define the variable c
before using it:
In this updated example, the variable c
is defined as the sum of a
and b
, and can now be returned without throwing a ReferenceError.
Conclusion
In conclusion, TypeError and ReferenceError are two common errors that can occur when working with JavaScript code. A TypeError occurs when a program attempts to perform an operation on a value that is not of the expected type, while a ReferenceError occurs when a program attempts to access a variable or object that does not exist. To avoid these errors, it's important to carefully check your code for misspelled variables or objects and ensure that you're using the correct data types in your operations.