Do you know these 7 common JavaScript errors?

We see errors everywhere, from browser consoles to computer terminals running Node.js.

The point of this post is to give an overview of the types of errors we can encounter during JS development.

1.  RangeError

This error is thrown when a number is outside the allowed range of values. For example:

const l = console.log
const arr = [90,88]
arr.length=90**99 

We have an arr with two elements. Next, we try to make the array contain 90**99 == 2.9512665430652753e+193 elements.

This number is beyond the range that the size array can grow. So when run it throws RangeError:

$ node errors
errors.js:4
arr.length=90**99
 ^
RangeError: Invalid array length

Because we want to increase the number of arr arrays beyond the range specified by JS.

2.  ReferenceError

This error is thrown when a reference to a variable/item is destroyed or does not exist. That is, the variable/item does not exist.

For example,

const l=console.log
const cat = "cat"
cat
dog 

We have a variable cat initialized to "cat". Next, we reference the cat variable and the dog variable. The cat variable exists, but the dog variable does not.

cat will return "cat", and dog will raise a ReferenceError because a variable named dog cannot be found in the environment record.

$ node errors
errors.js:3
dog
^
ReferenceError: dog is not defined

Whenever we create or define a variable, the variable name is written into the environment record. This environment record is like a key-value storage table, as shown in the following figure:

+-------------+
| Key | Value |
---------------
| cat | "cat" |
+-------------+

Whenever we refer to a variable, it stores the variable defined in the program. When an environment value is found in a record and the value is extracted and returned, the environment record is searched using the variable's name as a key. Call a function that has not been defined.

Now, when we create or define a variable without assigning a value. Variables will write the key as the variable name to the environment record, but the value will remain undefined.

var cat

env record
+-----------------+
| Key | Value     |
-------------------
| cat | undefined |
+-----------------+

When a variable is later assigned a value, the env record is searched for that variable, and when that initial undefined value is found, the assignment is overwritten.

var cat
cat = "cat"

env record
+-------------+
| Key | Value |
---------------
| cat | "cat" |
+-------------+

Therefore, the JS engine throws a RefernceError when the variable name is not found in the env record.

+-------------+
| Key | Value |
---------------
| cat | "cat" |
+-------------+
cat // "cat", yes, :) it's there
dog // :( what's this? can't find it

Note: An undefined variable does not throw a ReferenceError because it exists in the environment record just its value has not been set.

3.  SyntaxError

This is the most common error we encounter. This error occurs when we type code that is difficult for the JS engine to understand. During parsing, the JS engine caught this error.

In the JS engine, our code goes through different stages before we can see the running results on the terminal.

  • Tokenization

  • analyze

  • implement

Tokenization breaks down source code into individual units. At this stage, numbers, keywords, literals, operators will be classified and labeled separately. Next, the generated token stream is passed to the parsing stage, where it is processed by the parser. This is where the AST is generated from the token. AST is an abstract data structure for the structure of our code.

In the two stages of tokenization and parsing, if the syntax of our code does not conform to the grammar rules of JS, the execution stage will fail and SyntaxError will be raised. For example,

const l = console.log
let cat h =“ cat”

The "h" here is obviously redundant, so due to the extra character, the engine will throw a SyntaxError

$ node errors
errors.js:3
let cat h = "cat"
 ^

SyntaxError: Unexpected identifier

Obviously, the Node.js engine found an error, and the declaration of the cat variable failed due to the appearance of this dissonant character.

4.TypeError

TypeError refers to an error that occurs when the type used by an object to represent a value is not the expected type. For example, we expected it to be a boolean, but it turned out to be of type string.

Another example:

const num = 123
num.toUpperCase()

这会引发TypeError

$ node errors
errors.js:4
num.toUpperCase()
 ^
TypeError: num.toUpperCase is not a function

Because toUpperCase function expects string data type. The toUpperCase function is intentionally generic; it does not require its this value to be a String object. Therefore, it can be transferred to be used as a method in other kinds of objects.

If we call toUpperCase function on Objects, Boolean, Symbol, null, undefined data types, only strings will be converted to upper or lower case and we will get TypeError because it is operating on wrong data type.

5.  URIError

This illustrates that using a global URI handling function is incompatible with its definition.

URI (Uniform Resource Indicator) in JS has the following functions: decodeURI, decodeURIComponent, etc.

If we call any of these with the wrong arguments, we'll get a URIError .

decodeURI("%")
^

URIError: URI malformed

encodeURI, get the unencoded version of the URI. '%' is not a correct URI, so URIError is raised.

URIError is raised when there is a problem encoding or decoding the URI.

6.EvalError

If eval() is called illegally, an EvalError exception is thrown.

According to EcmaSpec 2018 edition:

This exception is no longer thrown by JavaScript, but the EvalError object remains for compatibility.

7. InternalError

The error happens inside the JS engine, especially when it has too much data to process and the stack grows past its critical limit.

This happens when the JS engine is overwhelmed with too much recursion, too many switch cases, etc.

switch(num) {
case 1:
...
break
case 2:
...
break
case 3:
...
break
case 4:
...
break
case 5:
...
break
case 6:
...
break
case 7:
...
break
... up to 1000 cases
}

Too much recursion, a simple example looks like this:

function foo() {
foo()
}
foo()

in conclusion

As we said, no one is free from mistakes. As far as the code we type is concerned, mistakes are inevitable.

But in order to avoid more errors, we need to know what type of error is thrown and how we can solve it.

So we list them in this article and provide some examples to briefly explain how they happen.

Guess you like

Origin blog.csdn.net/qq_41838305/article/details/130100221