Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / JavaScript

`console.log()` and `console.error()`: log levels versus exceptions

Use `console.log()` for routine diagnostics and `console.error()` for error-level messages. Writing an error message is not the same as throwing an exception.

Version: ECMAScript 2024 and the current web platform; runtime support varies

Syntax

console.log(...values)
console.log(format, ...substitutions)
console.error(...values)
console.error(format, ...substitutions)

console.log/error is shorthand for two methods on the global console namespace, not call syntax. console.log() writes a routine diagnostic message; console.error() writes at the error level. Both are part of the host-provided Console API, not ECMAScript 2024.

Both methods accept values as separate arguments or a format string as the first argument. Placeholders such as %s consume following arguments in order; extra values are displayed after the formatted text. On normal completion, both methods return undefined.

console.error() can take an Error object, but it does not require one. Reporting an error is not the same as throwing or catching an exception. If the call returns normally, execution continues. A logging call can still throw: for example, in Node.js, a custom inspection hook invoked while formatting an object can throw. Use throw to raise an exception explicitly.

Filters can hide messages. Presentation and whether a stack trace appears depend on the runtime. An object expanded later may show changes made after the call rather than its state at the time of logging. The console does not guarantee persistent storage. Do not log passwords, tokens, or personal data.

Examples

{
  const { Console } = require("node:console");
  const console = new Console({ stdout: process.stdout, stderr: process.stdout });
  const config = {};
  console.log("Checking %s", "config");
  if (!("port" in config)) {
    console.error("Missing field: %s", "port");
  }
  console.log("Execution continued");
}

Result

Checking config
Missing field: port
Execution continued

The first message shows `%s` substitution. A missing `port` field produces an error-level message, but the final `Execution continued` message shows that execution proceeds. This example configures a Node.js `Console` instance to send both log levels to standard output (`stdout`).

Related lessons

  • JavaScript · Lesson 42 · Advanced · Version: 4

Sources