search
HomeWeb Front-endJS TutorialJavaScript debugging tips you may not know

If you use a kind of code, you must first understand your tool. Once you are familiar with it, it can greatly help you complete the task. This article tells you some JavaScript debugging skills that you may not know. Although debugging JavaScript is very troublesome, you can still solve it in as little time as possible if you master the tricks. These are errors and bugs. I hope you can master JavaScript debugging skills that you may not know. Take one step further on our journey to accumulate code.


We will list 14 Debugging Tips that you may not know, but once you know it, you will be eager to debug next time Use them when writing JavaScript code!


Start now.


Most of the tips are for Chrome Inspector and Firefox, although many of the techniques can be used with other inspection tools as well.


1. 'debugger;'


'debugger' is my favorite debugger after console.log Tools, simple violence. Just write it into the code and Chrome will automatically stop there when it runs. You can even wrap it with a conditional statement so that it is executed only when needed.

if (thisThing) {
    debugger;
}



2. Output objects into a table


Sometimes you There may be a bunch of objects to look at. You can use console.log to output each object, or you can use the console.table statement to output them directly into a table!

var animals = [
    { animal: 'Horse', name: 'Henry', age: 43 },
    { animal: 'Dog', name: 'Fred', age: 13 },
    { animal: 'Cat', name: 'Frodo', age: 18 }
];
 
console.table(animals);


Output result:

JavaScript debugging tips you may not know



##3. Try all the sizes


#Although it looks cool to put all kinds of mobile phones on the table, it is very uncomfortable. Reality. Why not just resize the interface? Chrome provides everything you need. Go to the Inspector and click the ‘Switch Device Mode’ button so you can resize the window!

JavaScript debugging tips you may not know



4. How to quickly locate DOM elements



Mark a DOM element in the Elements panel and use it in the concole. Chrome Inspector's history saves the last five elements, with the last marked element marked as $0, the second to last marked element marked as $1, and so on.


If you mark the elements in order as 'item-4', 'item-3', 'item-2', 'item-1', 'item-0', you can get the DOM node in the concole:

JavaScript debugging tips you may not know



5. Use console.time() and console.timeEnd() to test loop time


This tool is used when you want to know the execution time of certain code This can be very useful, especially when you are locating time-consuming loops. You can even set multiple timers via tags. The demo is as follows:

console.time('Timer1');
 
var items = [];
 
for(var i = 0; i < 100000; i++){
   items.push({index: i});
}
 
console.timeEnd(&#39;Timer1&#39;);


## Running results:


JavaScript debugging tips you may not know


##6. Get the stack trace information of the function

You probably know that JavaScript frameworks generate a lot of code--quickly.

# It creates views that trigger events and you end up wondering how the function call happened.

#Because JavaScript is not a very structured language, it is sometimes difficult to fully understand what is happening and when. At this time, it’s console.trace’s turn (only trace in the terminal) to debug JavaScript.

Suppose you now want to see the complete stack trace information of the car instance calling the funcZ function on line 33:

var car;
var func1 = function() {
func2();
}
var func2 = function() {
func4();
}
var func3 = function() {
}
var func4 = function() {
car = new Car();
car.funcX();
}
var Car = function() {
this.brand = ‘volvo’;
this.color = ‘red’;
this.funcX = function() {
this.funcY();
}
this.funcY = function() {
this.funcZ();
}
this.funcZ = function() {
console.trace(‘trace car’)
}
}
func1();
var car; 
var func1 = function() {
func2();
} 
var func2 = function() {
func4();
}
var func3 = function() {
} 
var func4 = function() {
car = new Car();
car.funcX();
}
var Car = function() {
this.brand = ‘volvo’;
this.color = ‘red’;
this.funcX = function() {
this.funcY();
}
this.funcY = function() {
this.funcZ();
}
 this.funcZ = function() {
console.trace(‘trace car’)
}
} 
func1();

Line 33 will output:

JavaScript debugging tips you may not know


你可以看到func1调用了func2, func2又调用了func4。Func4 创建了Car的实例,然后调用了方法car.funcX,等等。


尽管你感觉你对自己的脚本代码非常了解,这种分析依然是有用的。 比如你想优化你的代码。 获取到堆栈轨迹信息和一个所有相关函数的列表。每一行都是可点击的,你可以在他们中间前后穿梭。 这感觉就像特地为你准备的菜单。


7. 格式化代码使调试 JavaScript 变得容易


有时候你发现产品有一个问题,而 source map 并没有部署到服务器。不要害怕。Chrome 可以格式化 JavaScript 文件,使之易读。格式化出来的代码在可读性上可能不如源代码 —— 但至少你可以观察到发生的错误。点击源代码查看器下面的美化代码按钮 {} 即可。

JavaScript debugging tips you may not know



8. 快速找到调试函数


来看看怎么在函数中设置断点。


通常情况下有两种方法:


1. 在查看器中找到某行代码并在此添加断点
2. 在脚本中添加 debugger


这两种方法都必须在文件中找到需要调试的那一行。


使用控制台是不太常见的方法。在控制台中使用 debug(funcName),代码会在停止在进入这里指定的函数时。


这个操作很快,但它不能用于局部函数或匿名函数。不过如果不是这两种情况下,这可能是调试函数最快的方法。(注意:这里并不是在调用 console.debug 函数)。

var func1 = function() {
func2();
};
 
var Car = function() {
this.funcX = function() {
this.funcY();
}
 
this.funcY = function() {
this.funcZ();
}
}
 
var car = new Car();


在控制台中输入 debug(car.funcY),脚本会在调试模式下,进入 car.funcY 的时候停止运行:

JavaScript debugging tips you may not know



9.  屏蔽不相关代码


如今,经常在应用中引入多个库或框架。其中大多数都经过良好的测试且相对没有缺陷。但是,调试器仍然会进入与此调试任务无关的文件。解决方案是将不需要调试的脚本屏蔽掉。当然这也可以包括你自己的脚本。 点此阅读更多关于调试不相关代码(http://raygun.com/blog/javascript-debugging-with-black-box/)。

JavaScript debugging tips you may not know



10. 在复杂的调试过程中寻找重点


在更复杂的调试中,我们有时需要输出很多行。你可以做的事情就是保持良好的输出结构,使用更多控制台函数,例如 Console.log,console.debug,console.warn,console.info,console.error 等等。然后,你可以在控制台中快速浏览。但有时候,某些JavaScrip调试信息并不是你需要的。


现在,可以自己美化调试信息了。在调试JavaScript时,可以使用CSS并自定义控制台信息:

console.todo = function(msg) {
console.log(‘ % c % s % s % s‘, ‘color: yellow; background - color: black;’, ‘–‘, msg, ‘–‘);
}
console.important = function(msg) {
console.log(‘ % c % s % s % s’, ‘color: brown; font - weight: bold; text - decoration: underline;’, ‘–‘, msg, ‘–‘);
}
console.todo(“This is something that’ s need to be fixed”);
console.important(‘This is an important message’);

输出:

JavaScript debugging tips you may not know



例如:


在console.log()中, 可以用%s设置字符串,%i设置数字,%c设置自定义样式等等,还有很多更好的console.log()使用方法。 如果使用的是单页应用框架,可以为视图(view)消息创建一个样式,为模型(models),集合(collections),控制器(controllers)等创建另一个样式。也许还可以像 wlog,clog 和 mlog 一样发挥你的想象力!


11. 查看具体的函数调用和它的参数


在 Chrome 浏览器的控制台(Console)中,你会把你的注意力集中在具体的函数上。每次这个函数被调用,它的值就会被记录下来。


var func1 = function(x, y, z) {

//....

};


然后输出:

JavaScript debugging tips you may not know



This is a great way to see what parameters are passed to a function. But I must say, it would be nice if the console could tell us how many parameters we need. In the above example, function 1 expects 3 parameters, but only 2 parameters are passed in. If the code is not handled in code, it can cause a bug.


12. Quickly access elements in the console


Execute querySelector in the console A faster way is Use the dollar sign. $(‘css-selector’) will return the first matching CSS selector. $$(‘css-selector’) will return all. If you use an element more than once, it deserves to be treated as a variable.

JavaScript debugging tips you may not know



13. Postman is great (but Firefox is faster)


Many developers use Postman to handle Ajax requests. Postman is really good, but every time you need to open a new browser window and write a new request object to test. This is actually a bit annoying.


Sometimes it's easier to just use the browser you're using.


#In this way, if you want to request a password-secured page, you no longer need to worry about verifying the cookie. This is how you edit and resend a request in Firefox.


Open the profiler and go to the network page, right-click on the request you want to process, select Edit and Resend. Now you can change it however you want. You can modify the header information or edit the parameters, and then click Resend.


Now I send the same request twice but with different parameters:

JavaScript debugging tips you may not know



14. Interrupt when the node changes


DOM is an interesting thing. Sometimes it changes and you don't know why. However, if you need to debug JavaScript, Chrome can pause processing when DOM elements change. You can even monitor its properties. On the Chrome profiler, right-click an element and select the Break on option to use

JavaScript debugging tips you may not know

The above are some tips on using JS, there are Friends who are doing research together can discuss it together.

Related reading:

The difference between JavaScript and ECMAScript


JavaScript implements drop-down menu Example


24 JavaScript Interview Questions


The above is the detailed content of JavaScript debugging tips you may not know. For more information, please follow other related articles on the PHP Chinese website!

Statement
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
JavaScript in Action: Real-World Examples and ProjectsJavaScript in Action: Real-World Examples and ProjectsApr 19, 2025 am 12:13 AM

JavaScript's application in the real world includes front-end and back-end development. 1) Display front-end applications by building a TODO list application, involving DOM operations and event processing. 2) Build RESTfulAPI through Node.js and Express to demonstrate back-end applications.

JavaScript and the Web: Core Functionality and Use CasesJavaScript and the Web: Core Functionality and Use CasesApr 18, 2025 am 12:19 AM

The main uses of JavaScript in web development include client interaction, form verification and asynchronous communication. 1) Dynamic content update and user interaction through DOM operations; 2) Client verification is carried out before the user submits data to improve the user experience; 3) Refreshless communication with the server is achieved through AJAX technology.

Understanding the JavaScript Engine: Implementation DetailsUnderstanding the JavaScript Engine: Implementation DetailsApr 17, 2025 am 12:05 AM

Understanding how JavaScript engine works internally is important to developers because it helps write more efficient code and understand performance bottlenecks and optimization strategies. 1) The engine's workflow includes three stages: parsing, compiling and execution; 2) During the execution process, the engine will perform dynamic optimization, such as inline cache and hidden classes; 3) Best practices include avoiding global variables, optimizing loops, using const and lets, and avoiding excessive use of closures.

Python vs. JavaScript: The Learning Curve and Ease of UsePython vs. JavaScript: The Learning Curve and Ease of UseApr 16, 2025 am 12:12 AM

Python is more suitable for beginners, with a smooth learning curve and concise syntax; JavaScript is suitable for front-end development, with a steep learning curve and flexible syntax. 1. Python syntax is intuitive and suitable for data science and back-end development. 2. JavaScript is flexible and widely used in front-end and server-side programming.

Python vs. JavaScript: Community, Libraries, and ResourcesPython vs. JavaScript: Community, Libraries, and ResourcesApr 15, 2025 am 12:16 AM

Python and JavaScript have their own advantages and disadvantages in terms of community, libraries and resources. 1) The Python community is friendly and suitable for beginners, but the front-end development resources are not as rich as JavaScript. 2) Python is powerful in data science and machine learning libraries, while JavaScript is better in front-end development libraries and frameworks. 3) Both have rich learning resources, but Python is suitable for starting with official documents, while JavaScript is better with MDNWebDocs. The choice should be based on project needs and personal interests.

From C/C   to JavaScript: How It All WorksFrom C/C to JavaScript: How It All WorksApr 14, 2025 am 12:05 AM

The shift from C/C to JavaScript requires adapting to dynamic typing, garbage collection and asynchronous programming. 1) C/C is a statically typed language that requires manual memory management, while JavaScript is dynamically typed and garbage collection is automatically processed. 2) C/C needs to be compiled into machine code, while JavaScript is an interpreted language. 3) JavaScript introduces concepts such as closures, prototype chains and Promise, which enhances flexibility and asynchronous programming capabilities.

JavaScript Engines: Comparing ImplementationsJavaScript Engines: Comparing ImplementationsApr 13, 2025 am 12:05 AM

Different JavaScript engines have different effects when parsing and executing JavaScript code, because the implementation principles and optimization strategies of each engine differ. 1. Lexical analysis: convert source code into lexical unit. 2. Grammar analysis: Generate an abstract syntax tree. 3. Optimization and compilation: Generate machine code through the JIT compiler. 4. Execute: Run the machine code. V8 engine optimizes through instant compilation and hidden class, SpiderMonkey uses a type inference system, resulting in different performance performance on the same code.

Beyond the Browser: JavaScript in the Real WorldBeyond the Browser: JavaScript in the Real WorldApr 12, 2025 am 12:06 AM

JavaScript's applications in the real world include server-side programming, mobile application development and Internet of Things control: 1. Server-side programming is realized through Node.js, suitable for high concurrent request processing. 2. Mobile application development is carried out through ReactNative and supports cross-platform deployment. 3. Used for IoT device control through Johnny-Five library, suitable for hardware interaction.

See all articles

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 Tools

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.