DEV Community

Ankur
Ankur

Posted on • Updated on

How to Debug Javascript Code

Javascript code Debugging tips.

Method 1: Stop execution control by putting the break point

use the "debugger" statement to create breakpoint and use F12 key to open console window on chrome browser;

example

function addIt(x,y){
debugger;
return x + y;
}

Method 2: Open console window of chrome browser (you can use shortcut key F12)

Click on source tab then Press Ctrl + P shortcut Key
type the script file name which you want to debug.
After opening a file you can put the breakpoint, it will be there until you removed it or disable it for your next run also.

Method 3: Modify the javascript code while debugging. just put breakpoint once execution control reaches on your breakpoint edit the code and press ctrl+s.
You will find that execution start again of that block once you saved it by ctrl+S.

Method 4: use console.log statement to check the variable value and debugging purpose.
console.log("********var1 = ",var1,"var2",var2);

Method 5: use console.time() and console.timeEnd() to get the execution time of a block of script.

//Example
function myFun(){
console.time();

//your function code here...
//...........

console.timeEnd();

}
you can also give a label to time function if you are using multipal console.time()

//Example
function myFun(){
console.time('myFunLbl1');

//your function code here...
//...........

//after some line you use
 console.time('myFunLbl2');
//.........
 console.time('myFunLbl2');
//.......
console.timeEnd('myFunLbl1');

}

Top comments (0)