Breakpoints in JavaScript
In this article, we will discuss the usage and benefits of breakpoint and how to debug our JavaScript code with the help of the debugger
keyword and the debugger mode of the browser.
Breakpoints
Most of the time, our program code contains few logical syntax errors, and our program is not providing the desired result as per given statements. So, to resolve errors and debug our program code, we need to stop the execution and check the execution flow on each step.
We use breakpoints in our programs to stop the execution, and various programming languages specifically contain breakpoints keywords.
Breakpoints keywords stop the execution during the run-time of code because most of the time, errors do not display any error messages or logs, and we need to find out what the actual problem is.
Breakpoints in JavaScript
Debugging is a tricky process, and now most browsers provide a built-in JavaScript debugger. We can set breakpoints with debuggers and define where we need to stop the execution.
We can examine the variable values at run-time while the execution of code.
We can activate debugging in our browser by pressing the F12 key, and from the debugger menu, select the Console
section. If our browser supports debugging, we can use the console.log()
method to display and examine the values.
Example of console
:
<!DOCTYPE html>
<html>
<body>
<h1>Delftstack learning</h1>
<h2>JavaScript debugger keyword example</h2>
<p>You can on debugger with F12 key and select console in debugger menu.</p>
<script>
a = 2;
b = 4;
sum = a + b;
console.log(c); // it will display the value of sum variable
</script>
</body>
</html>
In the above HTML source, we have used the console.log()
default method to display the sum of variables a
and b
; we can see the login console
section of debugger mode.
We can set breakpoints in the debugger window for the JavaScript code, and execution will be stopped at each breakpoint, which will help examine JavaScript values. We can resume the execution again with the play button in the debugger window.
Debugger
Keyword in JavaScript
The JavaScript debugger
keyword is used in code statements to stop the execution; it performs the same functionality as we set breakpoints in the debugger.
Example of debugger
:
<!DOCTYPE html>
<html>
<body>
<h1>Delftstack learning</h1>
<h2>JavaScript debugger keyword example</h2>
<p id="test"></p>
<p>You can on debugger and see the execution will be stop at third line.</p>
<script>
let sum = 15 + 5;
debugger; // to stop execution
document.getElementById("test").innerHTML = sum;
</script>
</body>
</html>
In the above HTML source, we have used debugger
keyword in JavaScript code to stop the execution and assign the sum
variable to the paragraph using getElementById("id").innerHTML
.