JAVASCRIPT

JavaScript Console Log: Printing to the Console in JS

In JavaScript, the console is a powerful debugging tool that provides access to a browser's debugging console. The console.log() method outputs messages to the web console, making it invaluable for debugging and displaying information.

How to Use the JavaScript Console

The console object contains a set of methods to interact with a browser's debugging console. These methods include log(), error(), warn(), and info().

console.log("This is a log message"); // Outputs a log message to the console
console.error("This is an error message"); // Outputs an error message to the console

  • console: The console object, which provides access to the debugging console.
  • log(), error(), warn(), info(): Methods to output different levels of messages.

When to Use JavaScript console.log

The JavaScript console is useful across different stages of development.

Debugging with console.log in JavaScript

console.log() can help you debug JavaScript code by logging values and expressions. You can follow an application or check variable values as the application runs.

Data Inspection

You can use console.log() to inspect JSON objects, arrays, or other data structures you get from an API.

Performance Monitoring

With console.time() and console.timeEnd(), you can also measure the time it takes to complete specific operations. Measuring execution time can help you find the issue when you notice performance bottlenecks.

Logging Errors

Finally, you can use console.log() to log errors to the console. Later on, you can use the error logs to find the underlying issues.

Examples of Console Log in JavaScript

Web Development Processes

During development, most web applications use console.log() to test components in a quick-and-dirty way.

let numbers = [1, 2, 3];
console.log("Numbers array:", numbers);

Errors and Exceptions

Most web applications also log errors to the console when catching exceptions, which aids in monitoring and troubleshooting.

try {
    // Code that might throw an error
    nonExistentFunction();
} catch (error) {
    console.error("Error occurred:", error);
}

Learn More About the JavaScript Console

Opening the Console

Any modern web browser offers a way to access its console. Here's how you can open the console in Google Chrome, Safari, or Firefox:

  • Google Chrome: Use Ctrl+Shift+J (Windows/Linux) or Cmd+Option+J (Mac) to open the console. Moreover, you can right-click on a web page, choose "Inspect", and then navigate to the "Console" tab.
  • Firefox: Use Ctrl+Shift+K (Windows/Linux) or Cmd+Option+K (Mac) to open the console within Firefox. To access the console through the menu, click the menu button, select "Web Developer," and then choose "Web Console."
  • Safari: Firstly, enable the Develop menu in the Preferences under the Advanced tab ( "Show Develop menu in menu bar"). Then use the Cmd+Option+C shortcut to open the console. You can also access the console by choosing "Develop" in the menu bar and selecting "Show JavaScript Console".

On Mimo, the JavaScript console is always visible in the Console tab when you run your code.

Advanced Console Methods

The console provides more than just console.log(); it includes console.table() for tabular data, console.group() to group messages, and console.assert() for conditional logging.

The console object provides more than just console.log(). It also includes other logging methods: console.table() for tabular data, console.group() to group messages, and console.assert() for conditional logging.

console.table([{ a: 1, b: 'Y' }, { a: 'Z', b: 2 }]);
console.assert(document.getElementById("demo"), "You have no element with ID 'demo'");

Custom Console Styling

Moreover, console.log() supports CSS styles, which is useful for making logs visually distinctive:

console.log("%cThis message is styled!", "color: blue; font-style: italic;");

Multi-line Console Logs

Multi-line template literals with backticks (````) allow embedded expressions and support string interpolation. For more complex logging requirements, template literals offer a clean and readable way to include various pieces of data:

let user = { name: "Alice", age: 25, role: "Admin" };
console.log(`Current User:
  Name: ${user.name}
  Age: ${user.age}
  Role: ${user.role}`);

JavaScript Printing to Console for User Notifications

While not recommended for production, you might find some web applications use console.log() to display information or warnings for tech-savvy users:

console.warn("This is a warning to developers using this console.");

JavaScript Console for Stack Traces

A stack trace is a report of the active stack frames at a certain point in time during the execution of a program. Getting a stack trace can be useful for debugging errors that involve multiple function calls.

JavaScript’s console.trace() method prints a stack trace to the console at the point where you call it. With console.trace(), you can visually follow the flow of execution to diagnose how variables and data structures change over time.

Here’s an example of getting a stack trace in JavaScript:

function firstFunction() {
  secondFunction();
}

function secondFunction() {
  thirdFunction();
}

function thirdFunction() {
  console.trace("Current execution trace");
}

firstFunction();
Learn JavaScript for Free
Start learning now
button icon
To advance beyond this tutorial and learn JavaScript by doing, try the interactive experience of Mimo. Whether you're starting from scratch or brushing up your coding skills, Mimo helps you take your coding journey above and beyond.

Sign up or download Mimo from the App Store or Google Play to enhance your programming skills and prepare for a career in tech.

You can code, too.

© 2024 Mimo GmbH