Overview
The most reliable way to confirm that a program is working as intended is to “see” the values of variables during execution. This article explains debugging techniques using the console.log() method. This method allows you to output information to the browser’s developer tools (console) and track calculation results or variable states in real-time.
Specifications (Input/Output)
- Input: Calling
console.log()within your JavaScript code. - Output: Displaying text, numbers, and object information in the browser’s Console tab.
Basic Usage
console.log() outputs the values passed as arguments to the browser’s console area. By passing multiple values separated by commas, you can display labels alongside values or check multiple variables at once.
Full Code (HTML / JavaScript)
HTML (index.html)
This is a simple screen that prompts the user to check the browser console.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Console Debugging Demo</title>
<script src="debug-demo.js" defer></script>
</head>
<body>
<div class="container">
<h1>Please check the Console</h1>
<p>Windows: F12 or Ctrl+Shift+I</p>
<p>Mac: Cmd+Option+I</p>
<p>Calculation results are displayed in the "Console" tab.</p>
</div>
</body>
</html>
JavaScript (debug-demo.js)
This script simulates a shopping cart calculation and outputs the process and results to the log.
/**
* Shopping cart calculation demo
*/
const calculateCart = () => {
// Define item price and tax rate
const itemPrice = 1500;
const taxRate = 0.1;
// Check a single value
console.log('--- Calculation Started ---');
console.log(itemPrice); // Outputs the number directly
// Calculation process
const taxAmount = itemPrice * taxRate;
const totalPrice = itemPrice + taxAmount;
// Output multiple values (using labels for clarity)
console.log('Tax Amount:', taxAmount);
console.log('Total Price:', totalPrice);
// Output using a template literal
console.log(`The tax-inclusive price for an item with a list price of ${itemPrice} yen is ${totalPrice} yen.`);
};
// Execute
calculateCart();
Customization Points
- Adding Identifiers: If you simply write
console.log(totalPrice), it becomes difficult to know “which value this is” as the number of logs increases. It is a good habit to add a string label, such asconsole.log('Total:', totalPrice), to improve readability. - Outputting Objects: If the variable is an object, wrapping it in curly braces like
console.log({ user })is helpful. This displays both the variable name and its contents as a set.
Important Points
- Leaving Logs in Production: Leaving
console.login your production (public) code can slow down processing and risk leaking internal logic. Always remove or disable them before release. - Outputting Sensitive Information: Never output passwords, API keys, or personal information to the logs. The console can be viewed by any user.
- Object References: If you log an object or array and then change its contents later in the code, some browsers might update the displayed log content (due to pass-by-reference). To record the exact value at a specific moment, you may need to clone it using
JSON.parse(JSON.stringify(obj)).
Advanced Usage
Outputting as Errors or Warnings
You can use different methods based on the importance of the information. This makes the console easier to read with color-coding.
// Warning (displayed with a yellow icon)
console.warn('Stock is running low');
// Error (displayed with a red icon and includes a stack trace)
console.error('Connection failed');
// Table format (neatly formats arrays or objects)
const users = [
{ id: 1, name: 'Alice' },
{ id: 2, name: 'Bob' }
];
console.table(users);
Summary
console.log is the most basic yet powerful debugging tool. Developing the habit of checking for gaps between “expected values” and “actual values” leads to early bug detection. However, be very careful not to forget to delete them before making your site public.
