Debugging JavaScript code in Chrome
Web developers need to know how to debug JavaScript code on Google Chrome. It enables you to locate and fix bugs in your code, improving the dependability of your web application.
Get Mbasamahmad’s stories in your inbox
Join Medium for free to get updates from this writer.
To grasp the debugging process, we should create a simple web application that takes a number as input and determines whether that number is prime or not. Let’s delve into building this application.
<!DOCTYPE html>
<html>
<head>
<title>Prime Number Checker</title>
</head>
<body>
<h1>Prime Number Checker</h1>
<label for="numberInput">Enter a Number:</label>
<input type="text" id="numberInput">
<button onclick="checkPrime()">Check Prime</button>
<p id="result"></p>
<script src="Debugging.js"></script>
</body>
</html>We are creating a simple web page for a Prime Number Checker web application in the above code.
- There’s an input field where users can enter a number. This input field has an
idattribute set tonumberInput, which can be used to uniquely identify it. - Below the input field, there’s a “Check Prime” button. When this button is clicked, an action is triggered.
- Below the button, there is an empty paragraph element with an
idattribute set toresultis provided. This paragraph will be used to display the result of whether the entered number is prime or not.
The HTML file includes an external JavaScript file named Debugging.js using the <script> tag. This JavaScript file likely contains the code for checking whether the entered number is prime or not. The code execution is linked to the button’s onclick attribute.
function isPrime(number) {
if (number < 2) {
return false;
}
for (let i = 2; i <= Math.sqrt(number); i++) {
if (number % i === 0) {
return false;
}
}
return true;
}
function checkPrime() {
const numberInput = document.getElementById("numberInput").value;
const resultElement = document.getElementById("result");
const number = parseInt(numberInput);// Convert input to a number
console.log("For the testing of console ");
if (!isNaN(number)) {
if (isPrime(number)) {
resultElement.textContent = `${number} is a prime number.`;
} else {
resultElement.textContent = `${number} is not a prime number.`;
}
} else {
resultElement.textContent = "Please enter a valid number.";
}
}To check number is prime or not, we define two functions: isPrime(number) and checkPrime() For the Prime Number Checker application. Let's break down what each function does:
isPrime(number):
- This function takes a single argument
numberto check whether it is prime or not. - It first checks if the number is less than
2. If it’s less than2, the function immediately returnsfalsebecause prime numbers are greater than 1. - Then, it enters a loop that starts from
2and goes up to the square root of the inputnumber. This loop checks if the input number is divisible by any integer within this range. - Inside the loop, it checks if the input number modulo
iis equal to0. If this condition is met for anyi, it means the number has a divisor other than 1 and itself, so it's not prime, and the function returnsfalse. - If the loop completes without finding divisors, the function returns, indicating that the input number is prime.
checkPrime():
- This function is called when the Check Prime button in your HTML form is clicked.
- It first retrieves the value entered in the input field with the
id"numberInput" usingdocument.getElementById("numberInput").valueand stores it in thenumberInputvariable. - It also retrieves the HTML element with the
id"result" and stores it in theresultElementvariable. This element will be used to display the result. - It then converts the
numberInputvalue to a number usingparseInt()and stores it in thenumbervariable. - It checks if the conversion was successful using
isNaN(). Ifnumberis not a valid number, it displays "Please enter a valid number" in theresultElement. - If
numberIt is a valid number and calls theisPrime(number)function to check if it's prime. - Depending on the result of the
isPrime()function, it updates thetextContentof theresultElementwith either "${number} is a prime number." or "${number} is not a prime number."
Open Developer Tools
You need to open the Google Chrome browser to debug the JavaScript code. After the browser is launched, you need to open the developer’s tools with the help of the following way:
- Right-click on the webpage and select “Inspect”.
- Press
Ctrl+Shift+Ion Windows to open Developer Tools. - Press
Cmd+Option+Ion macOS to open Developer Tools.
Navigate to the Sources tab
Once you open the Developer Tools, go to the Sources tab. In the left panel, you'll find a list of various files that make up your code.
Set Breakpoints
To debug a JavaScript file using the Chrome browser’s Developer Tools, first, locate the JavaScript file you want to debug in the left sidebar, usually under file:/// or the domain name of the website you're on.
- Click on the file to open it, then navigate to the specific line of code where you want to set a breakpoint.
- Click on the line number to set a breakpoint, indicated by a red dot, and this action will pause the execution of your code when that line is reached, allowing you to inspect variables and step through your code for debugging purposes.
Start Debugging
- Reload the webpage (
F5 or Ctrl+R / Cmd+R) or trigger the JavaScript code execution. - The execution will pause at the breakpoint, and the Debugger panel will appear.
You can deactivate breakpoints by clicking the breakpoint icon or removing them by right-clicking and selecting Remove breakpoint.
Debugger Panel
In the Debugger panel, you'll find controls to step through your code, including:
- Step Into (
F11orCmd+;): Go into functions. - Step Over (
F10orCmd+'): Execute the current line and move to the next line. - Step Out (
Shift+F11orCmd+Shift+;): Finish executing the current function. - Continue (
F8orCmd+Alt+;): Resume code execution until the next breakpoint.
Inspect variables and expressions
- While paused, you can inspect variables and expressions in the
ScopeandWatchsections of theDebuggerpanel. - Hover over variables in your code to see their current values.
Use Console for Logging and Evaluating Code
The Console tab in Developer Tools allows you to log messages and evaluate expressions in the current context.
Once you’ve identified and resolved the issue, you can continue executing the code until it completes or stops. When you’re done debugging, close the Developer Tools panel by clicking X in the top-right corner or pressing Ctrl+Shift+I again. Debugging JavaScript in Chrome is a powerful way to diagnose and fix issues in your web applications, making it an indispensable tool for web developers.





