Open In App

How to debug JavaScript File ?

Last Updated : 30 Jan, 2022
Improve
Improve
Like Article
Like
Save
Share
Report

Debugging is essential because there are many errors that are not giving any kind of messages so to find out that we debug the code and find out the missing point.

Example 1:  Using console.log() Method

In this, we can find out the error by consoling the code in various places. Using a console is one of the easy-to-use ways of debugging code in JavaScript. In our browser, the console is a command-line interface that helps in executing the snippets of code. So we can use this function to print our data and see what exactly went wrong.

HTML




<!DOCTYPE html>
<html>
  
<head>
    <meta charset="utf-8" />
    <meta http-equiv="X-UA-Compatible" 
        content="IE=edge" />
    <meta name="description" content="" />
    <meta name="viewport" content=
        "width=device-width, initial-scale=1" />
    <link rel="stylesheet" href="" />
</head>
  
<body>
    <script src="./index.js" async defer></script>
</body>
  
</html>


Filename: index.js

Javascript




var a;
console.log(a)
  
a = 20;
console.log(a)
  
a = "Geeks For Geeks";
console.log(a)


Output: Here we can see that the first console.log gives undefined because we just define the var a but does not assign any value. We can open the console by pressing the F12 key or by clicking the right button and then selecting inspect.

Example 2: Debugger Keyword

Javascript provides the keyword Debugger to debug the code. When we add the debugger keyword in between our code, so after executing the code, a debugger panel will show up where we can make breakpoints and play/pause to check the value and understand according to it. With the help of this debugger panel, we can see step by step execution of a program.

Javascript




var a;
console.log(a)
  
debugger
  
a = 20;
console.log(a)
  
a = "Hello World";
console.log(a)


Output: After writing the debugger keyword, when we run the code then in the console this kind of debugger panel will show up where we make breakpoints and play/pause to check the value and understand according to it. We can open the console by pressing the F12 key or by clicking the right button and then selecting inspect.

Breakpoints are the place where code stops running, by this if we are ever stuck in the infinite loop then we can trace it by this.



Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads