Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
How to Clear the JavaScript Console in Google Chrome
In this article, we'll learn how to clear the JavaScript console in Google Chrome. When developing web applications, the console often gets cluttered with logs, errors, and debug messages, making it difficult to read new output.
There are multiple ways to clear the Chrome console, each useful in different scenarios. Let's explore the most common methods.
Using the console.clear() Method
The console.clear() method programmatically clears the console and displays a "Console was cleared" message.
Example
<!DOCTYPE html>
<html lang="en">
<body>
<p>Click the button to clear the console.</p>
<button onclick="clearConsole()">Clear Console</button>
<script>
// Add some sample logs first
console.log("Message 1");
console.log("Message 2");
console.warn("Warning message");
function clearConsole() {
console.clear();
console.log("Console cleared programmatically!");
}
</script>
</body>
</html>
When you run this code and click the button, all previous console messages will be cleared.
Keyboard Shortcuts
You can quickly clear the console using keyboard shortcuts:
Windows/Linux:
Ctrl + LmacOS:
Cmd + K
These shortcuts work when the console panel is focused in Chrome DevTools.
Using the Clear Button
Chrome DevTools provides a clear button in the console toolbar. Look for the circular icon with a diagonal line through it in the top-left area of the console panel.
Comparison of Methods
| Method | When to Use | Leaves Message |
|---|---|---|
console.clear() |
Programmatic clearing | Yes - "Console was cleared" |
| Keyboard shortcuts | Quick manual clearing | No |
| Clear button | Manual clearing with mouse | No |
Practical Example
Here's a practical scenario where clearing the console is useful:
<!DOCTYPE html>
<html lang="en">
<body>
<button onclick="generateLogs()">Generate Sample Logs</button>
<button onclick="clearAndLog()">Clear & Start Fresh</button>
<script>
function generateLogs() {
for (let i = 1; i <= 5; i++) {
console.log(`Log message ${i}`);
console.warn(`Warning ${i}`);
}
}
function clearAndLog() {
console.clear();
console.log("Starting fresh debugging session...");
}
</script>
</body>
</html>
Conclusion
Clearing the console regularly helps maintain a clean debugging environment. Use console.clear() for programmatic clearing, keyboard shortcuts for quick manual clearing, or the clear button in DevTools for mouse-based clearing.
