11 Console Methods in JavaScript for Effective Debugging | Syncfusion Blogs
Live Chat Icon For mobile
Live Chat Icon
Popular Categories.NET  (173).NET Core  (29).NET MAUI  (207)Angular  (109)ASP.NET  (51)ASP.NET Core  (82)ASP.NET MVC  (89)Azure  (40)Black Friday Deal  (1)Blazor  (215)BoldSign  (14)DocIO  (24)Essential JS 2  (107)Essential Studio  (200)File Formats  (66)Flutter  (132)JavaScript  (220)Microsoft  (118)PDF  (81)Python  (1)React  (100)Streamlit  (1)Succinctly series  (131)Syncfusion  (912)TypeScript  (33)Uno Platform  (3)UWP  (4)Vue  (45)Webinar  (51)Windows Forms  (61)WinUI  (68)WPF  (158)Xamarin  (161)XlsIO  (36)Other CategoriesBarcode  (5)BI  (29)Bold BI  (8)Bold Reports  (2)Build conference  (8)Business intelligence  (55)Button  (4)C#  (147)Chart  (130)Cloud  (15)Company  (443)Dashboard  (8)Data Science  (3)Data Validation  (8)DataGrid  (63)Development  (625)Doc  (8)DockingManager  (1)eBook  (99)Enterprise  (22)Entity Framework  (5)Essential Tools  (14)Excel  (40)Extensions  (22)File Manager  (7)Gantt  (18)Gauge  (12)Git  (5)Grid  (31)HTML  (13)Installer  (2)Knockout  (2)Language  (1)LINQPad  (1)Linux  (2)M-Commerce  (1)Metro Studio  (11)Mobile  (505)Mobile MVC  (9)OLAP server  (1)Open source  (1)Orubase  (12)Partners  (21)PDF viewer  (43)Performance  (12)PHP  (2)PivotGrid  (4)Predictive Analytics  (6)Report Server  (3)Reporting  (10)Reporting / Back Office  (11)Rich Text Editor  (12)Road Map  (12)Scheduler  (52)Security  (3)SfDataGrid  (9)Silverlight  (21)Sneak Peek  (31)Solution Services  (4)Spreadsheet  (11)SQL  (10)Stock Chart  (1)Surface  (4)Tablets  (5)Theme  (12)Tips and Tricks  (112)UI  (386)Uncategorized  (68)Unix  (2)User interface  (68)Visual State Manager  (2)Visual Studio  (31)Visual Studio Code  (19)Web  (589)What's new  (331)Windows 8  (19)Windows App  (2)Windows Phone  (15)Windows Phone 7  (9)WinRT  (26)
11 Console Methods in JavaScript for Effective Debugging

11 Console Methods in JavaScript for Effective Debugging

JavaScript console methods allow developers to access the debugging console in web browsers. Developers can improve the application debugging process by using methods to print various messages on the browser console.

For example, the console.log() method helps us to print messages or data in the browser console. However, it is often overused since developers are unaware of other console methods.

In this article, I will discuss many of the JavaScript console methods available and how to use them in debugging.

1. Log method

The console.log() method is the most used JavaScript console method. It helps us to print strings, numbers, JavaScript objects, or variables in the console. In addition, it logs messages to a debugging terminal instead of presenting them in the browser console.

var testVariable = 404;
console.log("This is triggered by console.log")
console.log("checking the variable value",testVariable)

In the example above, I placed the console.log() method inside the function and passed a variable. When we execute the code, we will get an output like in the following screenshot.

Output of console log method in JavaScript

2. Info method

console.info() is a method similar to console.log(), but I recommend you to use console.info() to print any information required for debugging purposes instead of printing the values.

console.info("Testing the log info method")

The output from the above code is precisely the same as the output from the console.log() method.

Output of console info method in JavaScript

3. Debug method

In JavaScript, the console.log(), console.debug(), and console.info() methods are identical. The only difference is the way the output is visible in the browser console. The browser will define color codes to console method output messages. By default, output from the console.debug() method will not be visible in Chrome developer tools. You have to enable the console filter option for all levels to see the output from the debug method.

var userId = "UserOne";
var userId2 = "UserTwo";
var userId3 = "UserThree";

console.log("Console log"+ " " +  userId)

console.info("Console info" + " " +  userId2);

console.debug("Console debug" + " " +  userId3);

To get the console.debug() method output, you need to enable the Verbose debug level in dev tools in the dropdown shown in the following screenshot.

Enable the Verbose debug level in dev toolsNow you can see the console.debug() output below.

Output of console debug method in JavaScript

4. Warn method

The console.warn() method helps us to display a warning message in the console. We need to pass a message as a parameter. This message can be an object, array, or any variable.

var testVariable = 404;
var testObj = { firstname : "Ravidu", lastname : "Perera" };

console.warn("This is a Warning message")

// passing a variable
console.warn(testVariable)
   
// pass an object as a warning
console.warn(testObj)

The console output of this code follows.

Output of console warn method in JavaScriptAs you can see, the three warning messages are printed in the console with a warning sign. You can expand the warning message to see the details of the object as well.

5. Assert method

The console.assert() method is different from the previously discussed methods. It will only print the message in the console if the expression is evaluated as false. Therefore, you need to pass a Boolean expression as a method parameter.

let x = 1;
let y = 2;
console.assert(x + y == 4, "Expression is false")
console.assert(x + y == 3, "Expression is True")
console.assert(document.getElementById("Test"), "No element found with ID 'Test'");

In the above example, the first and the third statements are false. So, the output will be as follows.

Output of console assert method in JavaScript

6. Count method

We can use the console.count() method as a log counter. It logs the number of times the console.count() method has been called in the script. For example, if you use it inside a loop, you can find the number of times that loop is executed.

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

Output of console count method in JavaScript

Also, you can pass any label into the console.count() method as a parameter, and it will print the label name. For example, the following code will print each label until the loop ends. You can use any number of labels as a parameter to get the count. This will help you check whether your loop is working correctly and printing its output as expected.

If you call the console.count() method without passing any parameter, it will print the count with the “default” label.

for (i = 1; i <= 5; i++) {
  let firstLabel = "First Label"
  let secondLabel = "Second Label"

  console.count(firstLabel)
  console.count(secondLabel)
}

Output of console count method in JavaScript If you want to reset the counter, you can use the console.countReset() method. It also takes a parameter as a label. If you don’t pass anything, it will print “default” when the count is reset. The code looks like this.

for (i = 1; i <= 5; i++){
  let firstLabel = "First Label"
  let secondLabel = "Second Label"
  console.count(firstLabel );
}
console.countReset(firstLabel);

The output will look like this.

Output of console count method in JavaScript

7. Trace method

The trace method behaves exactly the same way as the console.log() method. The difference is that the console.trace() method will provide the stack trace. Basically, it will show the call path taken to reach the point where you put the console.trace() method.

Function TraceMethod(){
   function TestMethod(){
       console.trace(“Trace call”);
   }
   TestMethod();
}
TraceMethod();

We will get the following console output for the above code.

Output of console trace method in JavaScriptAs you can see, console.trace() method prints the given message as well as the trace. Here, TestMethod() is invoked initially and then TraceMethod() is invoked. You can see the line numbers of the method calls which are invoked in the code.

When the program is complicated and you can’t understand how certain methods are being called from different modules or files, this console.trace() method is very helpful.

8. Time, TimeLog, and TimeEnd methods

You can use the console.time() method to measure the execution time of the functions. It helps you improve application performance by identifying low-performing functions. For example, if you need to measure the performance of a for loop, you can use the console.time() method as shown below.

console.time("MyTimer")
for (var i = 0; i < addToCartButtons.length; i++) {
  var button = addToCartButtons[i];
  button.addEventListener('click', addToCartClicked)
}
console.timeEnd("MyTimer")

// MyTimer: 0.408935546875 ms

You can set up any number of timers on the same page. Just pass a unique label to identify the timer. Finally, you need to call the console.timeEnd() function to stop the timer. Make sure to call the same timer name inside the console.timeEnd() method as well.

Execution duration will print in milliseconds in the console. If you didn’t pass any label, it will print the time with the “default ” label.

9. Group, GroupEnd, and GroupCollapsed methods

You can generate a group of messages in the console using these methods. The group method also accepts a label as a parameter (optional), and you need to place it right before a console message to start the grouping.

console.log("This is the first level");

console.group("First group");
console.log("In the first group");

console.group("Second group");
console.log("In the second group under first group");
console.warn("Still in the second group");

console.groupEnd();

console.log("Back to the first group");
console.groupEnd();

The output of the above code will look like the following.

Output of console group and groupEnd methods in JavaScript

Passing a label to the console.group() method is not mandatory, but it helps developers identify which values are being grouped. However, console.groupEnd() does not require the group name since it always closes the most recently established logging group.

The console.groupCollapsed() method creates a new inline group in the console, but it is not like the group created in the console.group() method. This console.groupCollapsed() method will show the start of the collapsed message group and all the messages invoked after groupCollapsed(). You can pass a label as an optional parameter.

console.group("First group");
console.log("Main list 1");
console.log("Main list 2");
console.log("Main list 3"); 
console.groupCollapsed("Collapsed group");
console.log("List 1"); 
console.log("List 2"); 
console.log("List 3");  
console.groupEnd();

You need to expand the group to see the items inside.

Output of groupCollapsed method in JavaScript

10. Table method

When you have a complex set of objects, you will either use the console.log() method or scroll through the list of objects to inspect the issue. However, you can use the console.table() method to improve the debugging process in such situations. You can use it to report tabular versions of arrays and objects to the console. The tabular data format works beautifully, allowing you to understand your data better and debug your code quickly. You may also sort columns very fast. This method uses any object type, arrays, arrays of arrays, arrays of objects, and nested objects as a parameter.

As an object

If you pass an object, the index column represents the keys, and the value column represents the values that are related to the given key.

var user = {
  name:"Ravidu",
  age:25,
  job:"writer",
}

console.table(user);

Passing tabular data as an object in JavaScript

Array

The index column will have the indexes of the array starting from zero. Check this example and its output below.

var cities =["Washington","Delhi","London","Stockholm"];
console.table(cities);

Passing tabular data as an array in JavaScript

Arrays of arrays

In this case, column names will be increased as the index increases.

var Destinations =[["USA", "Washington"],["India","Delhi"],["UK","London"],["Sweden","Stockholm"]];
console.table(Destinations);

Passing tabular data as arrays of arrays in JavaScript

Arrays of objects

Here, values and properties are separated into columns.

var users = [
   {
       name: "Sam",
       age: 30
   },
   {
       name: "John",
       age: 45
   },
   {
       name: "Peter",
       age: 20
   }
];
console.table(users);

Passing tabular data as array of objects in JavaScript

Nested objects

Suppose your values are nested objects. The console.table() method labels the output index appropriately.

var roles = {
  writer: {
   firstname: "Ravindu",
   lastname: "Shehan", 
   email: "ravindu@gmail.com"
  }, 
  reviewer: {
   firstname: "Ravindu",
   lastname: "Shehan", 
   email: "ravindu@gmail.com"
  }
}

console.table (roles);

Passing tabular data as nested objects in JavaScript

11. Clear method

The clear() method helps you clean your browser console after all the debugging processes. You can use the console.clear() method before your debugging and at the end of it. It will ensure that no other printed messages are displayed in the console.

Easily build real-time apps with Syncfusion’s high-performance, lightweight, modular, and responsive JavaScript UI components.

Conclusion

There are so many methods and tools to debug in JavaScript, but console methods are one of the simplest and easiest techniques available. Moreover, since all the methods support almost every web browser, it is straightforward for developers to utilize these methods in debugging.

Fun fact: Developers define debugging as testing, finding, and correcting issues in computer programs. But the first known computer bug was an actual insect stuck in the computer that disrupted the electronics.

Happy debugging!

Syncfusion Essential JS 2 is the only suite you will ever need to build an app. It contains over 65 high-performance, lightweight, modular, and responsive UI components in a single package. Download a free trial to evaluate the controls today.

If you have any questions or comments, you can also contact us through our support forumssupport portal, or feedback portal. We are always happy to assist you!

Related blogs

Tags:

Share this post:

Popular Now

Be the first to get updates

Subscribe RSS feed

Be the first to get updates

Subscribe RSS feed