search
HomeWeb Front-endJS TutorialExperience in debugging Javascript scripts_javascript skills

As you learn more about programming in JavaScript, you will begin to understand the opaque error messages that JavaScript gives. Once you understand the common mistakes you make, you'll quickly know how to avoid them, so you'll write code with fewer and fewer errors.

Programming is actually a technology that continues to improve rapidly over time. But no matter how proficient you become, you still have to spend some time debugging your code. If you've done homework, or have experience programming in JavaScript, you'll know that a considerable amount of time is spent debugging. This is normal - it's just one of the things programmers have to do. In fact, according to numerous studies, programmers spend an average of fifty percent of their time solving bugs in their code.
The key is to learn how to debug your program effectively. I have some tips that can help you figure out why your program isn't running as it should, or help you avoid writing buggy code in the first place:
1. Print out variables in different ways
2. Watch out for common mistakes
 3. Think before coding
 ---------------------------------------- ------------------------------------------
If JavaScript fails to capture Your mistake, you also didn't find the error by looking at the code, sometimes printing out the variables will help you. The simplest way is to use an alert() like this:
// theGreeting gets a name using getName, then presents
// one or two alert boxes depending on what the name is
// function getName()
 {
  var first_name = prompt("what's your first name?","");
  var last_name = prompt("what's your last name?","");
var the_name = first_name " " last_name;
  alert("in getName, the_name is: " the_name);
 }
 -------------------------------- ----------Error found----------------------------------------- ------------
1. General program errors
Most of the errors are just boring syntax errors. Remembering to close those quotes, braces, and parentheses can take a long time, but luckily JavaScript's automatic error detector catches most of these errors. Although JavaScript error detectors continue to improve as browsers become more sophisticated, some errors will still slip through. Here are some common mistakes to look out for:
2. Confusing variable or function names
Errors caused by capitalizing and pluralizing variable and function names appear annoyingly often, and sometimes JavaScript error detectors don't catch them. By establishing and sticking to a naming convention for variables and functions, the number of these headaches can be greatly reduced. For example, I define variables in all lowercase letters, replace spaces with underscores (my_variable, the_data, an_example_variable), and use built-in symbols for functions (addThreeNumbers(), writeError(), etc.). I avoid using any plurals because I always forget whether those variables are plural or not.
3. Accidental use of reserved words
Some words cannot be used as variable names because they are already used by JavaScript. For example, you can't define a variable called "if" because that's actually part of JavaScript - if you use "if", you'll run into all kinds of trouble. When you're going crazy with variables named "if", it's tempting to have a variable named "document". Unfortunately, "document" is a JavaScript object. Another frequently encountered problem is naming variables "name" (form elements have a "names" attribute). Naming a variable "name" doesn't always cause problems, it just sometimes - and it's more confusing - is why you should avoid using "name" variables.
Unfortunately, different browsers have different reserved words, so there is no way to know which words to avoid. The safest bet is to avoid using words that are already part of JavaScript and used by HTML. If you have problems with variables and can't figure out what's wrong, try changing the variable's name. If successful, you may have avoided reserved words.
4. Remember to use two equal signs when making logical judgments
Some browsers can catch this error, but some cannot. This is a very common mistake, but it's hard to spot if your browser can't point it out for you. Here is an example of this error:
 var the_name = prompt("what's your name?", "");
 if (the_name = "the monkey")
 {
 alert(" hello monkey!");
 } else {
alert("hello stranger.");
 }
This code will generate the "hello monkey!" alert dialog - regardless of where you are in the prompt What's knocking - this is not what we want. The reason is that there is only one equal sign in an if-then statement, which tells JavaScript that you want one thing to be equal to another. Let’s say you typed “robbie the robot” in the prompt. Initially, the value of the variable the_name is "robbie the robot", but then the if statement tells JavaScript that you want to set the_name to "the monkey." So JavaScript happily executes your command and sends a "true" message to the if-then statement, resulting in the warning dialog box showing "hello monkey!" every time. This insidious mistake can drive you crazy, so be careful to use two equal signs.
5. Accidentally quoted the variable, or forgot to quote the string
I run into this problem from time to time. The only way JavaScript distinguishes variables from strings is that strings have quotes, variables don't. There is an obvious error below:
var the_name = 'koko the gorilla';
alert("the_name is very happy");

Although the_name is a variable, the program will also generate a A warning dialog box prompting "the_name is very happy," appears. This is because once JavaScript sees something surrounded by quotes it no longer considers it, so when you put the_name in quotes, you prevent JavaScript from looking up it from memory. Here's a less obvious extension of this type of error:
Function wakeMeIn3()
{
var the_message = "Wake up! Hey! Hey! WAKE UP!!!!";
setTimeout ("alert(the_message);", 3000);
 }
 The problem here is that you tell JavaScript to execute alert(the_message) after three seconds. However, after three seconds the_message will no longer exist because you have exited the function. This problem can be solved like this:
function wakeMeIn3()
{
var the_message = "Wake up!";
setTimeout("alert('" the_message "');", 3000);
 }
Put the_message outside the quotation marks, and the command "alert('Wakeup!');" is scheduled by setTimeout, and you can get what you want. These are just some of the hard-to-debug bugs that might be causing trouble in your code. Once they are discovered, there are different better and worse ways to correct them. You're lucky because you get to benefit from my experience and mistakes.
 --------------------------------Clear errors------------- -----------------------
Finding errors, although sometimes difficult, is only the first step. Then you have to clear the error. Here are some things you should do when clearing errors:

Make a copy of your program first
Some errors are difficult to clear. In fact, sometimes when eradicating a bug, you break the entire program - one little bug drives you crazy. Saving your program before starting to debug is the best way to ensure that bugs don't take advantage of you.
Fix one error at a time
If you know there are several errors, you should fix one, check the results, and then start the next one. Fixing many errors at once without verifying your work will only invite more errors.
Beware of confusing errors
Sometimes you know there is an error but don’t really know why. Suppose there is a variable "index". For some reason "index" is always 1 less than you expect. You can do one of two things: sit there for a while and figure out why it got smaller, or just shrug; add 1 before using "index" and move on. The latter approach is called obfuscation programming. You're applying a bandage to the tape when you start thinking, "What the hell - why is index 2 instead of 3? Well... I'll make it work now and fix it later." A potential flaw.
Obfuscated programming may work in the short term, but you can see long-term doom - if you don't fully understand your code to the point where you can actually clean up the bug, that bug will come back to haunt you. It either comes back as another weird bug that you can't fix, or when the next poor damned soul reads your code, he'll find it extremely difficult to understand.
Looking for Small Bugs
Sometimes, the ability to cut and paste code is a bad thing for programmers. Typically, you'll write some JavaScript code in a function and then cut and paste it into another function. If there was a problem with the first function, now there is a problem with both functions. I'm not saying you shouldn't cut and paste code. But bugs have a way of multiplying, and if you find one bug you should look for other bugs that are similar to it. (Or know exactly what to expect before making several versions of it.) Variable name misspellings will crop up many times in a piece of JavaScript code - misspell the_name instead of teh_name in one place, and you'll have a chance of finding it elsewhere. mistake.
If all else fails
If you're sitting there staring at an error and can't figure out what's going on (or you don't see the error at all, but you know there's an error because the program doesn't run correctly ), you'd better walk away from the computer. Go read a book, take a walk around the corner, or grab a nice drink - do something, anything, but don't think about the program or the problem. This technique is called "brewing" in some situations, and it works very well. After you take a break and relax, try to find the mistake again. You'll get a clearer picture. Brewing works because it frees you from mental clutter. If you go too far down a wrong path, you sometimes find you can't turn around. In this case it is best to create a new path. I know this is infuriating, but it works. real!
If the above method is not successful...
Ask others for help. Sometimes your thinking becomes stereotyped, and only by looking at it differently can you gain insight into the problem. In a structured programming environment, programmers review each other's code regularly. This is appropriately called "code review" and will not only help eliminate errors but also result in better code. Don't be afraid to show others your JavaScript code, it will make you a better JavaScript programmer.
 
  But the absolute best way to eliminate errors is...
  Create error-free code in the first place.
 --------------------------------Create error-free code---------- ----------------------------
The key to programming well is that programs are written for people, not for computers. If you can understand that others may read your JavaScript, you'll write cleaner code. The clearer the code, the less likely you are to make mistakes. Clever code is lovely, but it's this clever code that creates bugs. The best rule of thumb is KISS, which stands for Keep It Simple, Sweetie. Another helpful technique is to comment before writing code. This forces you to think before you act. Once the comment is written, you can write code underneath it.
Here is an example of writing a function in this way:
Step 1: Write comments
Step 2: Fill in the code
This strategy of writing comments first not only forces you to write comments before writing code Think and make the coding process look easier - By breaking the task into small, easy-to-code pieces, your problem will look less like Mount Everest and more like a group of pleasantly rolling hills.
Finally... always end each of your statements with a semicolon.
Although not strictly required, you should get into the habit of ending each statement with a semicolon to avoid having code after that line. Forget the semicolon and the next line of good code will suddenly produce an error. Initialize variables to "var" unless you have a better reason not to. Using "var" to localize variables reduces the chance of confusing one function with another unrelated function.
Okay, now that you know how to code, let’s learn how to make
your JavaScript run fast. >>
 ------------------------------------------------ ----------------
Optimize JavaScript code according to speed
1. Limit the workload within the loop
2. Customize the if-then-else statement to the most likely The most unlikely sequence
3. Minimize repeated expressions

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
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.

Building a Multi-Tenant SaaS Application with Next.js (Backend Integration)Building a Multi-Tenant SaaS Application with Next.js (Backend Integration)Apr 11, 2025 am 08:23 AM

I built a functional multi-tenant SaaS application (an EdTech app) with your everyday tech tool and you can do the same. First, what’s a multi-tenant SaaS application? Multi-tenant SaaS applications let you serve multiple customers from a sing

How to Build a Multi-Tenant SaaS Application with Next.js (Frontend Integration)How to Build a Multi-Tenant SaaS Application with Next.js (Frontend Integration)Apr 11, 2025 am 08:22 AM

This article demonstrates frontend integration with a backend secured by Permit, building a functional EdTech SaaS application using Next.js. The frontend fetches user permissions to control UI visibility and ensures API requests adhere to role-base

JavaScript: Exploring the Versatility of a Web LanguageJavaScript: Exploring the Versatility of a Web LanguageApr 11, 2025 am 12:01 AM

JavaScript is the core language of modern web development and is widely used for its diversity and flexibility. 1) Front-end development: build dynamic web pages and single-page applications through DOM operations and modern frameworks (such as React, Vue.js, Angular). 2) Server-side development: Node.js uses a non-blocking I/O model to handle high concurrency and real-time applications. 3) Mobile and desktop application development: cross-platform development is realized through ReactNative and Electron to improve development efficiency.

The Evolution of JavaScript: Current Trends and Future ProspectsThe Evolution of JavaScript: Current Trends and Future ProspectsApr 10, 2025 am 09:33 AM

The latest trends in JavaScript include the rise of TypeScript, the popularity of modern frameworks and libraries, and the application of WebAssembly. Future prospects cover more powerful type systems, the development of server-side JavaScript, the expansion of artificial intelligence and machine learning, and the potential of IoT and edge computing.

Demystifying JavaScript: What It Does and Why It MattersDemystifying JavaScript: What It Does and Why It MattersApr 09, 2025 am 12:07 AM

JavaScript is the cornerstone of modern web development, and its main functions include event-driven programming, dynamic content generation and asynchronous programming. 1) Event-driven programming allows web pages to change dynamically according to user operations. 2) Dynamic content generation allows page content to be adjusted according to conditions. 3) Asynchronous programming ensures that the user interface is not blocked. JavaScript is widely used in web interaction, single-page application and server-side development, greatly improving the flexibility of user experience and cross-platform development.

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 Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
1 months agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

Atom editor mac version download

Atom editor mac version download

The most popular open source editor

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),