Home >Web Front-end >JS Tutorial >What are the common types of errors in JavaScript? (detailed introduction)
In JavaScript, when an error occurs, an error object describing the error type will be generated. This error object contains information such as the error type and number. This information can be used for subsequent processing. In this article, we will introduce common Types of errors and how to handle them.
#What are the common types of errors in JavaScript?
The following three error types are common in JavaScript
RangeError
ReferenceError
SyntaxError
Let’s talk about Let’s take a look at the reasons why these three errors occur respectively
The reason why RangeError occurs
RangeError occurs when the value contained in a variable or parameter exceeds the valid range. An error occurred.
For example, if the following code is executed, RangeError will be raised.
var myarray = new Array(-1)
The execution results are as follows.
Uncaught RangeError: Invalid array length
In the above code, I create a new Array object in the variable of myarray.
But there was a problem when creating the Array object and an error occurred.
Because the given parameters for constructing a new Array object are illegal values.
If written as new Array(5), the parameter must be a number greater than 0 in order to create an Array object containing 5 elements.
Therefore, -1 is considered invalid and an error occurs.
Why ReferenceError occurs
ReferenceError is an error that occurs when trying to reference data that cannot be referenced.
It happens in the following situations
console.log(myvar)
The execution results are as follows.
Uncaught ReferenceError: myvar is not defined
In the above code, the error occurs because it is trying to output the value of the variable myvar which does not exist.
In this way, not only a variable that does not exist is referenced, but the same error will also occur in variables outside the scope.
The reason why SyntaxError occurs
SyntaxError mainly occurs when there is a problem with grammar writing.
It happens in the following situations.
console.log("Hello world!)
The execution results are as follows.
Uncaught SyntaxError: Invalid or unexpected token
In the above code, I am trying to display Hello world in JavaScript console! , but since I'm not outputting the string with full quotes, it's considered illegal writing.
If you write console.log("Hello world!"), it will execute normally without error.
The above is the detailed content of What are the common types of errors in JavaScript? (detailed introduction). For more information, please follow other related articles on the PHP Chinese website!