Javascript Debugging

It’s important to debug any code to minimize the risk of error. Being a scripting language, JavaScript didn’t show any error message in a browser. But these mistakes can affect the output.

The best practice to find out the error is to debug the code. The code can be debugged easily by any web browsers like Google Chrome, Mozilla Firefox.

We can find out errors using built-in web browser debugger. To perform debugging, we can use any of the following approaches:-


Using console.log()

This method displays the result in the console of the browser. If it finds any mistake in the code, it generates the error message.

To open console, press F12 or right click on browser, then click on inspect element. In this panel, go to second tab with name Console.

Input:-
 <script>  
	   x = 10;  
    y = 15;  
    z = x + y;  
    console.log("The value of z is ",z);  
    console.log("The value of a is ",a);
</script>

Output:-

         Like we are initializing variable in above example and try to output that variable                  in console. It helps in checking the value of any variable.


Using debugger/ breakpoints

We set breakpoints to examine each line of code step by step. There is no requirement to perform this task manually in JavaScript.

JavaScript provides debugger keyword to set the breakpoint through the code itself. The debugger stops the execution of the program at the position it is applied.

Now, we can start the flow of execution manually. After examining values, we can resume the execution of code (typically with a play button).

To make debugger active we should open inspect element using F12 or right click on browser and then click on Inspect element.

Input:-
 <script>  
	   x = 10;  
    y = 15;  
    z = x + y;  
	   debugger;
    console.log("The value of z is ",z);  
    console.log("The value of a is ",a);
</script>

Output:-