JavaScript Console
The console object provides access to the browser's debugging console. It's essential for debugging JavaScript code, logging information, and measuring performance.
F12 and click the "Console" tab. In PlayCode, the console output appears in the Console panel on the right. console.log()
The most commonly used method. Outputs messages to the console:
// Single value
console.log("Hello, World!");
// Multiple values (separated by space)
console.log("Name:", "Alice", "Age:", 25);
// Variables
const message = "Debug info";
console.log(message);
// Expressions
console.log(2 + 2); // 4
console.log("Result:", 10 * 5); // Result: 50Log Levels
Different methods for different types of messages:
// Regular log
console.log("Normal message");
// Informational (blue icon in browser)
console.info("User logged in successfully");
// Warning (yellow background)
console.warn("API is deprecated, use v2 instead");
// Error (red background, shows stack trace)
console.error("Failed to fetch data");
// Debug (may be hidden by default in browser)
console.debug("Detailed debug information");| Method | Use Case | Styling |
|---|---|---|
| console.log() | General output | None |
| console.info() | Informational | Blue icon |
| console.warn() | Warnings | Yellow background |
| console.error() | Errors | Red background |
| console.debug() | Debug info | May be hidden |
Logging Objects
Console methods handle objects and arrays intelligently:
const user = {
name: "Alice",
age: 25,
address: {
city: "New York",
zip: "10001"
}
};
// Log object
console.log(user);
// Log with label
console.log("Current user:", user);
// console.dir shows object properties
console.dir(user);
// Destructure in log
const { name, age } = user;
console.log({ name, age }); // { name: "Alice", age: 25 }console.table()
Displays tabular data as a table:
// Array of objects
const products = [
{ id: 1, name: "Laptop", price: 999 },
{ id: 2, name: "Mouse", price: 29 },
{ id: 3, name: "Keyboard", price: 79 }
];
console.table(products);
// Select specific columns
console.table(products, ["name", "price"]);
// Simple array
console.table(["Apple", "Banana", "Cherry"]);
// Object
console.table({ a: 1, b: 2, c: 3 });console.table() is perfect for debugging arrays of objects. You can even sort by clicking column headers in the browser console. Performance Timing
Measure how long operations take:
// Basic timing
console.time("fetch");
// ... some operation
console.timeEnd("fetch"); // fetch: 123.45ms
// Multiple timers
console.time("total");
console.time("step1");
// ... step 1
console.timeEnd("step1");
console.time("step2");
// ... step 2
console.timeEnd("step2");
console.timeEnd("total");
// Time log (doesn't stop timer)
console.time("process");
// ... partial work
console.timeLog("process", "halfway done");
// ... more work
console.timeEnd("process");Grouping Output
Organize related logs into collapsible groups:
// Basic group
console.group("API Request");
console.log("URL: /api/users");
console.log("Method: GET");
console.log("Status: 200");
console.groupEnd();
// Collapsed by default
console.groupCollapsed("Response Data");
console.log("Large data here...");
console.log("More data...");
console.groupEnd();
// Nested groups
console.group("User Actions");
console.group("Login");
console.log("Validated credentials");
console.log("Created session");
console.groupEnd();
console.group("Dashboard");
console.log("Loaded widgets");
console.groupEnd();
console.groupEnd();Styled Output
Add CSS styling to console output (browser only):
// Styled console output (browser only)
console.log(
"%cHello %cWorld",
"color: blue; font-size: 20px;",
"color: red; font-weight: bold;"
);
// Multiple styles
console.log(
"%c Success! %c Data saved",
"background: green; color: white; padding: 2px 6px; border-radius: 3px;",
"color: gray;"
);
// Warning style
console.log(
"%c⚠️ Warning",
"color: orange; font-size: 16px; font-weight: bold;"
);Try It Yourself
Experiment with different console methods:
// Basic logging
console.log("Hello, Console!");
console.log("Multiple", "arguments", 123, true);
// Log levels
console.info("ℹ️ Info message");
console.warn("⚠️ Warning message");
console.error("❌ Error message");
// Logging objects
const user = { name: "Alice", age: 25 };
console.log("User object:", user);
// Console.table for arrays/objects
const users = [
{ name: "Alice", age: 25 },
{ name: "Bob", age: 30 },
{ name: "Charlie", age: 35 }
];
console.table(users);
// Timing
console.time("loop");
for (let i = 0; i < 1000000; i++) {}
console.timeEnd("loop");
// Counting
console.count("click");
console.count("click");
console.count("click");Try advanced features like grouping and tracing:
// Grouping related logs
console.group("User Details");
console.log("Name: Alice");
console.log("Age: 25");
console.log("Email: alice@example.com");
console.groupEnd();
// Collapsed group
console.groupCollapsed("Server Response");
console.log("Status: 200");
console.log("Data: { success: true }");
console.groupEnd();
// Assertions (only logs if condition is false)
console.assert(1 === 1, "This won't show");
console.assert(1 === 2, "This will show - assertion failed!");
// Clear console
// console.clear();
// Stack trace
function first() { second(); }
function second() { third(); }
function third() { console.trace("Trace from third()"); }
first();
// Dir for DOM elements (in browser)
console.dir({ nested: { object: { here: true } } });Best Practices
console.error() for errors, console.warn() for warnings. This makes filtering easier. console.table() is much more readable than console.log(). console.group() to organize related logs, especially in complex operations. Quick Reference
log()General outputerror()Error with stack tracewarn()Warning messagetable()Tabular displaytime()Start timertimeEnd()End timergroup()Start groupgroupEnd()End groupcount()Count callsassert()Conditional logtrace()Stack traceclear()Clear consoleTest Your Knowledge
Test Your Knowledge
4 questionsWhich console method outputs with red styling?
How do you display an array as a table?
What does console.time() do?
What does console.assert(false, "message") do?
Practice Exercise
Create a Debug Logger
Build a logger object with info, warn, and error methods that include timestamps.
// Challenge: Create a debug logger with different levels
// The logger should:
// 1. Show a timestamp with each message
// 2. Support different levels: info, warn, error
// 3. Format output nicely
const logger = {
info(message) {
// TODO: Log with timestamp and "INFO" prefix
},
warn(message) {
// TODO: Log with timestamp and "WARN" prefix using console.warn
},
error(message) {
// TODO: Log with timestamp and "ERROR" prefix using console.error
}
};
// Test the logger
logger.info("Application started");
logger.warn("Cache is getting full");
logger.error("Database connection failed");
Frequently Asked Questions
Does console.log affect performance?
Yes, especially when logging large objects or in loops. Console operations are synchronous and can slow down your code. Remove or disable logs in production.
How do I log to a file instead of console?
In browsers, you cannot write to files directly. In Node.js, use the fs module or a logging library like Winston or Pino for file-based logging.
Why does my object show "[object Object]"?
This happens when you concatenate an object with a string: "User: " + obj. Instead, use comma separation: console.log("User:", obj) or JSON.stringify(obj).
Summary
The console object is your primary debugging tool in JavaScript:
- console.log() for general output
- console.error() and console.warn() for issues
- console.table() for arrays and objects
- console.time() for performance measurement
- console.group() for organizing output
Remember to remove console statements from production code for better performance and security.