Home Web Front-end JS Tutorial A brief summary of common errors in JavaScript development

A brief summary of common errors in JavaScript development

Jan 02, 2021 am 11:03 AM
javascript

As a front-end workerJavaScript, of course the more experience you have, the easier it will be to troubleshoot errors. We all know the principles, but we still don’t know how to proceed when we encounter a problem.

A brief summary of common errors in JavaScript development

Recommended (Free): JavaScript (Video)

Common in Chrome DevTools Error troubleshooting

The Console of Chrome Developer Tools is quite easy to use. The most commonly used one is to display the results of variables or operations through console.log. If it meets expectations Then everyone is happy.

But once a red letter appears and tells us "you made a mistake!", it is undoubtedly a setback for us. When we don't know how to solve the error, we can only check our code repeatedly. Check to see if there is anything strange. Sometimes even if you stop at the wrong place, you often don’t know what it means, so you will spend a lot of time.

This article will introduce common error feedback and troubleshooting techniques in Chrome developer tools, so that you will no longer be frustrated by red letters filling the screen, and learn how to quickly search for error codes.

Note: JavaScript is a synchronous programming language. If an error occurs, the subsequent code will not be able to run. When the red letter is not resolved, it may cause the next line of code to be incorrect or unable to run. Continue running .

Error type: SyntaxError

SyntaxError type of error is usually a syntax error. It is recommended when encountering this error Troubleshoot through the IDE you are using, such as VSCode, which can directly jump out of this type of error prompt.

As shown below, VSCode uses a red wavy line to prompt that the family object has an error. When an error occurs, it is recommended not to just check the current line. The error may exist in the context (may span multiple line error), in this example, careful inspection can reveal that there is a missing comma after 'Xiao Ming'.

A brief summary of common errors in JavaScript development

Troubleshooting focus: Use mainstream IDE such as "VSCode" for troubleshooting

Uncaught SyntaxError: Unexpected identifier

var person = {
  name: '小明'
  family: {
    name: '小明家'
  }
}
Copy after login

Syntax parsing error, because a comma is missing in the object structure. In addition to viewing it in VSCode, you can also directly switch to the Source page through Chrome Console to view the error line, and check whether there is a syntax error in the context of this line.

A brief summary of common errors in JavaScript development

Uncaught SyntaxError: Unexpected end of input

function fn() {
  console.log('这是一个函数');
console.log(fn);
Copy after login

Syntax parsing error: Unexpected end, the end is missing in this example Braces }, try to maintain the correct locking when writing code. It is easier to find errors after arranging the code neatly.

A brief summary of common errors in JavaScript development

Uncaught SyntaxError: Unexpected token '}'

if (name)
  console.log('立即执行函数')
};
Copy after login

A brief summary of common errors in JavaScript development

Syntax parsing error: Unexpected token The expected symbol }, and there is an extra } symbol at the end of the code, causing an environment operation error. The troubleshooting method for this error is the same as above. Try to arrange the code neatly and maintain the consistency of the first and last symbols. .

In addition, I recommend a VSCode tool that can add corresponding colors to your first and last tags: https://marketplace.visualstu...

Example: Pairs in the code The {} will be displayed in the same color.

A brief summary of common errors in JavaScript development

Uncaught SyntaxError: Identifier 'a' has already been declared

let a;
let a;
Copy after login

Syntax parsing error: Identifier 'a' has already been declared is a variable) has been declared, you should avoid repeating the same variable. In ES6, it is prohibited to use let and const to declare variables repeatedly, just exclude them directly.

Error type: ReferenceError

ReferenceError This type of error usually means that the reference cannot be found. When this type of error occurs, it is not displayed in the IDE. An error will definitely be prompted (unless Linter is installed), so you will only see this type of error during the running phase of the code.

Troubleshooting focus:

  • Correction through Chrome prompts
  • Install ESLint in the JavaScript development environment

##ReferenceError: a is not defined

ReferenceError: a is not defined
Copy after login

引用错误:由于变量 a 未定义,所以在使用这个变量时会出现未定义的提示,只要先定义好这个变量即可。

还有另一种很常见的情况,当引用外部包时出现 “包名 + is not defined”,这种情况通常是外部资源没有被正确载入,应该确保该资源被正确的引入。

下面的例子就是因为 jQuery 没有正确导入而导致的。

Uncaught ReferenceError: $ is not defined
Copy after login

错误类型:TypeError

TypeError 是类型上的错误,同样 IDE 也不会预先提示有错误,必须在执行时才会看到,这类型的错误通常是以下几种:

  • 试图获取 undefined、null 的属性
  • 尝试调用非函式变量或表达式(例如: 'text'()
排查重点:在获取变量前先确认其当前的数据类型及结构

Uncaught TypeError: Cannot read property 'a' of undefined

var a;
console.log(a.a);
Copy after login

说明:在这个变量的值中无法找到其特定的属性,例如在 undefined、null 的值上是找不到其它属性的,如果无法确认该变量是否为 undefined,可以把代码改成这样:

if (typeof a !== 'undefined') {
  console.log(a.a);
}
Copy after login

Uncaught TypeError: console.log(...) is not a function

console.log('a')
(function() {
  console.log('立即执行函数')
})()
Copy after login

说明:这代码看起来是立即执行函数的错误,但是却出现了 console.log(...) is not a function。这个错误主要是因为缺少了分号。

当遇到这类错误时只要在两者之间补上分号即可。

console.log('a');
(function() {
  console.log('立即执行函数')
})()
Copy after login

错误类型:RangeError

这是创建了超过长度上限的数组或执行了无法退出的递归函数所造成的错误,遇到这类问题需要重新检查代码的逻辑,是否消耗了过多的资源(内存或CPU资源)。

排查重点:需要重新检查逻辑,如果有必要可先删除部分代码,先找出错误的片段后再进行除错。

Uncaught RangeError: Maximum call stack size exceeded

(function a() {
  a();
})();
Copy after login

说明:在函数调用时会产生一个函数调用栈,如果在递归的过程中超过上限则会产生错误。

这类错误也很常见,却不容易找到出错的原因,其主要原因是在递归时超过了环境的限制(使用框架时也很常见),如果遇到这错误建议改写当前调用函数的方式。

总结

当 Chrome Console 报错时要保持淡定,在编码的过程中出现错误是很常见的,所谓的大佬与新手之间的区别之一就是遇到错误时的经验,遇到错误时搞不清楚没关系,这都是经验的累积。只要积累足够了,再遇到相同的问题时就能自然而然的轻松面对了。

The above is the detailed content of A brief summary of common errors in JavaScript development. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
2 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Repo: How To Revive Teammates
1 months ago By 尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island Adventure: How To Get Giant Seeds
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How to implement an online speech recognition system using WebSocket and JavaScript How to implement an online speech recognition system using WebSocket and JavaScript Dec 17, 2023 pm 02:54 PM

How to use WebSocket and JavaScript to implement an online speech recognition system Introduction: With the continuous development of technology, speech recognition technology has become an important part of the field of artificial intelligence. The online speech recognition system based on WebSocket and JavaScript has the characteristics of low latency, real-time and cross-platform, and has become a widely used solution. This article will introduce how to use WebSocket and JavaScript to implement an online speech recognition system.

WebSocket and JavaScript: key technologies for implementing real-time monitoring systems WebSocket and JavaScript: key technologies for implementing real-time monitoring systems Dec 17, 2023 pm 05:30 PM

WebSocket and JavaScript: Key technologies for realizing real-time monitoring systems Introduction: With the rapid development of Internet technology, real-time monitoring systems have been widely used in various fields. One of the key technologies to achieve real-time monitoring is the combination of WebSocket and JavaScript. This article will introduce the application of WebSocket and JavaScript in real-time monitoring systems, give code examples, and explain their implementation principles in detail. 1. WebSocket technology

How to implement an online reservation system using WebSocket and JavaScript How to implement an online reservation system using WebSocket and JavaScript Dec 17, 2023 am 09:39 AM

How to use WebSocket and JavaScript to implement an online reservation system. In today's digital era, more and more businesses and services need to provide online reservation functions. It is crucial to implement an efficient and real-time online reservation system. This article will introduce how to use WebSocket and JavaScript to implement an online reservation system, and provide specific code examples. 1. What is WebSocket? WebSocket is a full-duplex method on a single TCP connection.

How to use JavaScript and WebSocket to implement a real-time online ordering system How to use JavaScript and WebSocket to implement a real-time online ordering system Dec 17, 2023 pm 12:09 PM

Introduction to how to use JavaScript and WebSocket to implement a real-time online ordering system: With the popularity of the Internet and the advancement of technology, more and more restaurants have begun to provide online ordering services. In order to implement a real-time online ordering system, we can use JavaScript and WebSocket technology. WebSocket is a full-duplex communication protocol based on the TCP protocol, which can realize real-time two-way communication between the client and the server. In the real-time online ordering system, when the user selects dishes and places an order

JavaScript and WebSocket: Building an efficient real-time weather forecasting system JavaScript and WebSocket: Building an efficient real-time weather forecasting system Dec 17, 2023 pm 05:13 PM

JavaScript and WebSocket: Building an efficient real-time weather forecast system Introduction: Today, the accuracy of weather forecasts is of great significance to daily life and decision-making. As technology develops, we can provide more accurate and reliable weather forecasts by obtaining weather data in real time. In this article, we will learn how to use JavaScript and WebSocket technology to build an efficient real-time weather forecast system. This article will demonstrate the implementation process through specific code examples. We

Simple JavaScript Tutorial: How to Get HTTP Status Code Simple JavaScript Tutorial: How to Get HTTP Status Code Jan 05, 2024 pm 06:08 PM

JavaScript tutorial: How to get HTTP status code, specific code examples are required. Preface: In web development, data interaction with the server is often involved. When communicating with the server, we often need to obtain the returned HTTP status code to determine whether the operation is successful, and perform corresponding processing based on different status codes. This article will teach you how to use JavaScript to obtain HTTP status codes and provide some practical code examples. Using XMLHttpRequest

How to get HTTP status code in JavaScript the easy way How to get HTTP status code in JavaScript the easy way Jan 05, 2024 pm 01:37 PM

Introduction to the method of obtaining HTTP status code in JavaScript: In front-end development, we often need to deal with the interaction with the back-end interface, and HTTP status code is a very important part of it. Understanding and obtaining HTTP status codes helps us better handle the data returned by the interface. This article will introduce how to use JavaScript to obtain HTTP status codes and provide specific code examples. 1. What is HTTP status code? HTTP status code means that when the browser initiates a request to the server, the service

How to use insertBefore in javascript How to use insertBefore in javascript Nov 24, 2023 am 11:56 AM

Usage: In JavaScript, the insertBefore() method is used to insert a new node in the DOM tree. This method requires two parameters: the new node to be inserted and the reference node (that is, the node where the new node will be inserted).

See all articles