0
0
JavascriptHow-ToBeginner · 3 min read

How to Use console.error in JavaScript: Simple Guide

Use console.error() in JavaScript to print error messages to the console, which helps in debugging by highlighting problems. It works like console.log() but shows messages as errors, often in red color.
📐

Syntax

The console.error() method takes one or more arguments and prints them as error messages in the console.

  • console.error(message1, message2, ...): Logs error messages.
  • message1, message2, ...: Any values or expressions you want to show as errors.
javascript
console.error('Error message');
console.error('Error:', new Error('Something went wrong'));
Output
Error message Error: Error: Something went wrong
💻

Example

This example shows how to use console.error() to display an error message when a condition fails.

javascript
function divide(a, b) {
  if (b === 0) {
    console.error('Cannot divide by zero!');
    return null;
  }
  return a / b;
}

const result = divide(10, 0);
console.log('Result:', result);
Output
Cannot divide by zero! Result: null
⚠️

Common Pitfalls

Some common mistakes when using console.error() include:

  • Using console.log() instead of console.error() for errors, which can make debugging harder.
  • Passing complex objects without stringifying, which may not display clearly in some consoles.
  • Not checking conditions before logging errors, causing unnecessary error messages.
javascript
/* Wrong way: Using console.log for errors */
console.log('Error: File not found');

/* Right way: Using console.error for errors */
console.error('Error: File not found');
Output
Error: File not found
📊

Quick Reference

MethodPurposeExample
console.error()Logs error messages in red or error styleconsole.error('Error occurred')
console.log()Logs general informationconsole.log('Info message')
console.warn()Logs warning messagesconsole.warn('Warning message')

Key Takeaways

Use console.error() to clearly mark error messages in your JavaScript console.
console.error() accepts multiple arguments like console.log().
Prefer console.error() over console.log() for errors to improve debugging clarity.
Avoid logging errors unnecessarily by checking conditions before calling console.error().
console.error() output often appears in red or with error icons in developer tools.