🖥️ Console Functions in JavaScript
The JavaScript console is a tool located in the browser's DevTools that allows you to:
- Write code snippets.
- See results instantly.
- Show messages, errors, and warnings.
Accessing the console
To open it, you can use keyboard shortcuts (like Ctrl + Shift + J or F12, depending on the browser and operating system).
In the DevTools, there is a tab called "Console" which is where you will write and see the messages.
console.log()
It is the most used method. It serves to display text, results, or variables in the console.
console.log("Hello World");
console.log(2 + 2);
console.log("Result:", 5 + 18);
Error messages by levels
Although console.log() is one of the most used methods (sometimes the only one), there are many others. For example, the DevTools console has a system to filter error messages by levels. Instead of using the popular console.log(), we can use the console.warn(), console.error() method, etc:
| Function | Description |
|---|---|
console.debug() | Detailed information (lowest level). |
console.info() | General information. |
console.warn() | Warnings (appears in yellow). |
console.error() | Errors (appears in red). |
Group messages in the console
JavaScript allows you to visually organize messages in the console using a series of grouping methods. This is useful when we want to:
- Read long outputs more easily.
- Show related data as a block.
- Hide technical information that can be expanded if needed.
Available methods:
| Function | Description |
|---|---|
console.group() | Starts an expandable group with the indicated text as a title. |
console.groupCollapsed() | Starts a collapsed (closed) group by default. |
console.groupEnd() | Ends the current group. |
Example:
console.group("Browser information");
console.log("User Agent:", navigator.userAgent);
console.log("Language:", navigator.language);
console.groupEnd();
console.log("This message is outside the group");