How do I print a message to the error console using JavaScript?

To print messages to the browser console in JavaScript, use the console object. Different methods display messages with varying styles and importance levels.

Basic Console Methods

Here are the main console methods for displaying messages:

console.log("This is a regular message");
console.error("This is an error message");
console.warn("This is a warning message");
console.info("This is an info message");
This is a regular message
This is an error message (displayed in red)
This is a warning message (displayed in yellow/orange)
This is an info message (displayed in blue)

Error Console Specifically

To print specifically to the error console, use console.error(). This displays messages in red and may include stack trace information:

let errorMessage = "Something went wrong!";
console.error(errorMessage);

// With variable formatting
let errorCode = 404;
console.error("Error code: %d", errorCode);
Something went wrong! (displayed in red)
Error code: 404 (displayed in red)

Styling Console Messages

You can add CSS styling to console messages using the %c directive:

console.log("%c Styled message!", "background: green; color: white; padding: 5px;");
console.error("%c Critical Error!", "background: red; color: white; font-weight: bold;");
Styled message! (displayed with green background and white text)
Critical Error! (displayed with red background, white text, and bold font)

Comparison of Console Methods

Method Purpose Display Color
console.log() General information Default (black/white)
console.error() Error messages Red
console.warn() Warning messages Yellow/Orange
console.info() Informational messages Blue

Practical Example

Here's a practical example showing different console methods in a typical error handling scenario:

function validateAge(age) {
    console.info("Starting age validation");
    
    if (age < 0) {
        console.error("Age cannot be negative: %d", age);
        return false;
    }
    
    if (age > 120) {
        console.warn("Age seems unusually high: %d", age);
    }
    
    console.log("Age validation completed successfully");
    return true;
}

// Test the function
validateAge(-5);
validateAge(150);
validateAge(25);
Starting age validation (blue)
Age cannot be negative: -5 (red)
Starting age validation (blue)
Age seems unusually high: 150 (yellow/orange)
Age validation completed successfully (default)
Starting age validation (blue)
Age validation completed successfully (default)

Conclusion

Use console.error() for error messages, console.warn() for warnings, and console.log() for general information. These methods help categorize and visually distinguish different types of messages in the browser's developer console.

Updated on: 2026-03-15T22:23:39+05:30

355 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements