JavaScript Console

Beginner 5 min read

The console object provides access to the browser's debugging console. It's essential for debugging JavaScript code, logging information, and measuring performance.

Open the Console
In a browser, press 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:

javascript
// 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: 50

Log Levels

Different methods for different types of messages:

javascript
// 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");
MethodUse CaseStyling
console.log()General outputNone
console.info()InformationalBlue icon
console.warn()WarningsYellow background
console.error()ErrorsRed background
console.debug()Debug infoMay be hidden
Note
In browser DevTools, you can filter console output by level. Use the appropriate level to make debugging easier.

Logging Objects

Console methods handle objects and arrays intelligently:

javascript
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:

javascript
// 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 });
Perfect for Arrays
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:

javascript
// 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:

javascript
// 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):

javascript
// 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;"
);
Warning
Styled console output works in browsers but not in Node.js. Use it sparingly for important messages.

Try It Yourself

Experiment with different console methods:

index.js
// 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:

index.js
// 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

1. Use Appropriate Log Levels
Use console.error() for errors, console.warn() for warnings. This makes filtering easier.
2. Remove Logs in Production
Console statements slow down code and expose internal info. Remove or disable them in production builds.
3. Use console.table for Data
When debugging arrays of objects, console.table() is much more readable than console.log().
4. Group Related Logs
Use console.group() to organize related logs, especially in complex operations.

Quick Reference

log()General output
error()Error with stack trace
warn()Warning message
table()Tabular display
time()Start timer
timeEnd()End timer
group()Start group
groupEnd()End group
count()Count calls
assert()Conditional log
trace()Stack trace
clear()Clear console

Test Your Knowledge

Test Your Knowledge

4 questions
Question 1

Which console method outputs with red styling?

Question 2

How do you display an array as a table?

Question 3

What does console.time() do?

Question 4

What does console.assert(false, "message") do?

Practice Exercise

Create a Debug Logger

Easy

Build a logger object with info, warn, and error methods that include timestamps.

Starter Code
// 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.