How to Debug Javascript

The ability to debug code is an essential tool in any programmer's arsenal. Debugging will give you inside information into how your program is functioning, in real-time, as it runs. Javascript offers a unique but familiar method of...

Method 1 of 2:

Using the Debugger; Statement

  1. Picture 1 of How to Debug Javascript
    Determine if debugger; is the correct tool for this situation. Ask yourself:
    1. Do I need to look at this in great detail?
    2. Do I want to know the values, and the path the program is taking?
    3. Can I effectively test this through the developer window?
  2. Picture 2 of How to Debug Javascript
    Before the problem area, enter the statement: debugger;
  3. Picture 3 of How to Debug Javascript
    Open your browser's developer tools by right clicking and selecting inspect element. This will be browser specific, but they should all work very similarly.
  4. Picture 4 of How to Debug Javascript
    Once inside of developer tools, run your code again. This time it will stop at the debugger; statement.
  5. Picture 5 of How to Debug Javascript
    Step through your program, line-by-line, by pressing F10.
  6. Picture 6 of How to Debug Javascript
    Repeat the process as necessary. You may have to restart your program to trigger the debugger; again.
  7. Picture 7 of How to Debug Javascript
    Once you've used the debugger to solve the problem, be sure to remove the statement when you're done.
Method 2 of 2:

Using an Alert();

  1. Picture 8 of How to Debug Javascript
    Determine if alert(); is the correct tool for this situation. Ask yourself:
    1. Do I only need to know if a certain part of the program is running?
    2. Do I only want to know one value, and timing is not important?
  2. Picture 9 of How to Debug Javascript
    After the problem area, enter the statement: alert();
    1. Note that this alert will print, "This is an alert." To the screen. This could be any value.
  3. Picture 10 of How to Debug Javascript
    Run your code as normal.
    1. Once this point is reached, it will create a popup on your screen with whatever information put into the argument of alert();
  4. Picture 11 of How to Debug Javascript
    Use the information from the alert(); to solve the issue.
    1. Is alert(); printing what I expect it to?
    2. Is alert(); printing at all?
  5. Picture 12 of How to Debug Javascript
    Repeat the process as necessary. You may have to restart your program to trigger the alert(); again.
  6. Be certain to remove the alert(); statement when you're done.
Picture 13 of How to Debug Javascript
Update 05 March 2020
Category

System

Mac OS X

Hardware

Game

Tech info

Technology

Science

Life

Application

Electric

Program

Mobile