JavaScript Console Methods

The console object is a powerful tool for debugging and monitoring the JavaScript code's execution. It can help us track variables, identify issues, and gain insights into the behavior of your program.

The console object is commonly used for debugging purposes, logging information, and testing code. It allows us to output messages, errors, warnings, and other information to the console, which can help in understanding the flow and behavior of our code.

The debugging console of the browser is accessible through the console object.

The console object is a powerful tool for debugging and monitoring the JavaScript code’s execution. It can help us track variables, identify issues, and gain insights into the behavior of your program.

1. console.assert( ) Method

The console.assert() method is used in JavaScript to test a condition and display an error message in the console if the condition is false. It provides a way to check assertions in your code and is often used for debugging and identifying issues during development.

const x = 6;
const y = 5;
console.assert(x + y === 11, "The expression is incorrect");
console.assert(x + y === 12, "The expression is incorrect");

Output – Console

The result will be empty for true statements

console.assert(x + y === 11, "The expression is incorrect");

For console.assert(x + y === 12, "The expression is incorrect"); the result will be as below in case of incorrect statements

Assertion failed: The expression is incorrect script.                   js:-- 

2. console.clear( ) Method

Console clear method is used to clear all previous outputs displayed in console.


console.clear();

Output

There is an easier method to clear console

Click on Ctrl + L inside the console to clear all console outputs.

3. console.count( ) Method

The console.count() method is used to count the number of times a specific label or expression is logged to the console. It helps in tracking how many times a particular code block or condition is executed. 

for (let i = 0; i < 5; i++) {
  console.count();
}

let gameScore = "";

function scoreOrder() {
  console.count(gameScore);
}

scoreOrder(12);
scoreOrder(15);

gameScore = "T";

scoreOrder(18);
scoreOrder(21);

Output

4. console.countReset( ) Method

Count Reset Method is used alongside count method to reset the counter to zero.

console.count("Teczpert");
console.count("Teczpert");
console.countReset("Teczpert");
console.count("Teczpert");

Output

5. console.debug( ) Method

The console.debug is identical to console.log method. Debug messages are hidden by default in console.debug which is the only difference between them.

console.debug(`${"T"}${"ECZPERT"}`);

The output to console will be empty by default.

If we need to see the output click on default levels and ensure verbose is selected. Then the output will be displayed in the console.

6. console.dir( ) Method

The console.log() outputs the object as a string representation, but console.dir() outputs the object’s properties and recognizes it as an object.

The console.dir() method in JavaScript is used to display an interactive listing of the properties of a specified JavaScript object. It allows you to explore the object’s properties and their values in a structured manner.

console.dir() is useful for inspecting and exploring the properties of complex objects, providing a more detailed and interactive view in the console. console.log() is suitable for general-purpose logging and displaying simple values or messages.


const teczpert = {
  website: "teczpert.com",
  domain: ".com",
};


console.log(teczpert);
console.dir(teczpert);

Output

7. console.error( ) Method

This primary purpose of this method is to output an error message to the Web console.

let x = 20;
let y = 0;

function calculation(x, y) {
  if (y === 0) {
    console.error("Division by number 0 is not allowed⚠️");
  } else {
    const result = x / y;
    console.log(`The result of ${x}/${y} is ${result}`);
  }
}

calculation(x, y);

x = 10;
y = 5;

calculation(x, y);

8. console.group( ) Method , console.groupCollapsed( ) Method and console.groupEnd( ) Method

console.group( ) Method

The console.group() method in JavaScript is a part of the Console API, which is used for debugging and logging information in the browser’s developer console. This method allows us to group and organize the console log messages into collapsible and expandable groups, making it easier to navigate and understand the log output, especially when dealing with complex code or multiple log messages.

console.groupCollapsed( ) Method

Similar to console.group(), it opens a new group in the console, but it starts as collapsed, so the messages within it are hidden until the user expands the group.

console.groupEnd() Method

This method closes the most recently opened group, whether it was created using console.group() or console.groupCollapsed(). It marks the end of the current group.

function teczpertDigital() {
  console.group("Teczpert Digital Solutions Portal");
  console.log("We offer software development solutions");

  for (let i = 0; i < 3; i++) {
    console.groupCollapsed(`Teczpert Services Listing ${i + 1}`);
    console.log("Product 1");
    console.groupEnd();
  }

  console.groupEnd();
  console.group("Thankyou for your digital services");
  console.warn("If you proceed further then do it at your own discretion ⚠️");
  console.groupEnd();
}
teczpertDigital();

9. console.info( ) Method

console.info() is specifically intended for informational messages. It is often used to provide information or updates that are not errors or warnings but are still valuable for developers and users to know.

console.info("Teczpert is a famous website");
console.log("Teczpert is a famous website");

Firefox Console – There is an i icon for console.info which means that it is informative message and not a warning message. In chrome console it will not be seen.

10. console.log( ) Method

console.log is a function in JavaScript used for logging information to the console, which is typically the browser’s developer console or the console in a Node.js environment. It’s commonly used for debugging and monitoring the execution of the code.

Benefits of console.log:

  1. Debugging: It helps find and fix issues in the code by providing insights into the values of variables, the flow of your program, and error messages.
  2. Monitoring: It can be used to track the execution of the code, especially in complex applications, to see what’s happening at different points in the code.
  3. Learning: console.log is a valuable tool for learning and understanding how the code works, especially for beginners.
const nepal = {
  country: "Nepal",
  capital: "Kathmandu",
  population: "30 million",
};

try {
  throw new Error("Custom error: Data is unavailable");
} catch (error) {
  console.log(`Caution ⚠️ ${error.message}`);
} finally {
  console.log(nepal);
}

11. console.profile( ) Method and console.profileEnd( )

These methods are used for profiling the execution of JavaScript code within the browser’s developer tools.

12. console.table( ) Method

console.table() is a method in the JavaScript console object that is used to display tabular data in a more organized and readable format within the browser’s developer console or the console in a Node.js environment. It takes an array or an object as its argument and presents the data as an interactive table.

const france = {
  country: "France",
  capital: "Paris",
  population: "67 million",
};

console.table(france);

13. console.time( ), console.timeEnd( ), console.timeLog( ), and console.timeStamp( ) Method

  1. console.time(label): This method starts a new timer with the given label. You can have multiple timers running simultaneously with different labels.
  2. console.timeEnd(label): This method stops the timer associated with the provided label and logs the elapsed time in milliseconds since console.time() was called.
  3. console.timeLog(label[, data]): This method logs a message to the console with the specified label, along with optional additional data. It’s useful for logging intermediate information while a timer is running.
  4. console.timeStamp(label): This method adds a timestamp to the console log with the provided label. Timestamps can be used to mark significant points in the execution of your code.
console.time("timerOne"); // Start a timer with label "timerOne"

for (let i = 0; i < 1000000; i++) {
  // Simulate a time-consuming operation
  Math.sqrt(i);
}

console.timeLog("timerOne", "Iteration completed"); // Log an intermediate message

for (let i = 0; i < 500000; i++) {
  // Simulate another time-consuming operation
  Math.log(i);
}

console.timeEnd("timerOne"); // Stop the timer and log the elapsed time

console.timeStamp("Important Point"); // Add a timestamp with label "Important Point"
console.log("Important Point:", new Date().toISOString()); //Another approach for above line as console timeStamp may not be shown in most consoles.

console.time("timerTwo"); // Start another timer with label "timerTwo"

// Simulate a different time-consuming operation
for (let i = 0; i < 2000000; i++) {
  Math.sin(i);
}

console.timeEnd("timerTwo"); // Stop the second timer and log the elapsed time

14. console.trace() Method


console.trace()
is a method in the JavaScript console object that is used to log a stack trace to the console. A stack trace provides information about the sequence of function calls that led to the current point in the code’s execution.

Benefits of console.trace():

  1. Debugging: It is a valuable tool for debugging because it helps you understand the call hierarchy of functions leading to a specific point in your code. This can be especially useful for tracking down the source of errors and unexpected behavior.
  2. Troubleshooting: It assists in troubleshooting issues by revealing the execution path and the order in which functions were called.
  3. Profiling: It can be used for performance profiling to identify which functions are consuming the most time and resources.

The stack trace helps you trace the order of function calls, making it easier to identify where in the code an issue or event originated. This can be extremely valuable for debugging and troubleshooting complex applications.

function teczpert() {
  console.trace("Trace and Analyze teczpert");
  console.log("Analysis completed");
}

teczpert();

15. console.warn() Method

The console.warn() method in JavaScript is used to log warning messages to the console. It provides several benefits in the development and debugging process:

  1. Highlighting Potential Issues: console.warn() is typically used to alert developers about potential problems in the code. When you log a warning message, it signals that there’s something that should be reviewed or addressed. It’s a way to catch issues before they become critical errors.
  2. Differentiating from Regular Logs: In the console, warning messages are often displayed with a distinctive visual style (e.g., an orange or yellow warning icon) to make them stand out from regular log messages. This makes it easier for developers to notice warnings and prioritize them during debugging.
  3. Communicating Intent: Using console.warn() in your code communicates your intent to other developers or yourself. It says, “This part of the code may have issues or requires attention.” This can be valuable when working on collaborative projects or when returning to your own code after some time.
  4. Identifying Problems in a Timely Manner: By logging warnings, you can quickly identify potential issues, even if they don’t immediately cause errors. This can help you catch and fix problems in the early stages of development before they escalate into critical errors that are harder to debug.
  5. Documentation: Warnings can serve as a form of documentation within the codebase. They provide context and explanations about why a particular piece of code might be problematic or need special attention.
  6. Logging Conditional Execution: console.warn() is often used in conditional statements to log messages when specific conditions are met. This is especially helpful for tracking the behavior of the code under different scenarios.

Use console.warn() to notify about issues that may affect the program’s behavior or correctness but are not critical errors. It’s often used for non-blocking issues or to provide a heads-up to developers.

Use console.error() to log messages that indicate issues causing program failures or incorrect behavior. It’s intended for situations that require immediate attention, debugging, and fixing.

console.warn(`Proceed with caution`);