DEV Community

Cover image for The browser console has a count method
Christian Heilmann
Christian Heilmann

Posted on • Originally published at christianheilmann.com

The browser console has a count method

When debugging or analysing JavaScript, you often see people trying to find out how often a certain function is called. The common way to do that is to use a global counter variable to increment and log in the function.

var i = 0;
function test(){
  // other functionality
  i++;
  console.log(i);
  // other functionality
}
Enter fullscreen mode Exit fullscreen mode

There is, however, a better method. The Console of the browser has a count() and countReset() method that event takes a label. That means you can avoid the global.

function bettertest(){
  console.count('bettertest');
}
Enter fullscreen mode Exit fullscreen mode

You can see it in action in this screencast.

Screencast of the two ways to count how often a method was called in comparison

This is part of the standard Console API and should be supported in all browsers.

Top comments (1)

Collapse
 
nickytonline profile image
Nick Taylor

TIL!