I’ve been using Console.log , the browser’s default debugger, since day one of my JavaScript programming journey. Did you know there are many other useful console functions available?

In this article, I will cover few useful console functions. We will first start with most common console.log

Console.log:

The log() method writes (logs) a message to the console.

Console.log using Braces:

  • When you print the objects using console.log as shown below, log does not show your object name.
  • Now use the braces (i.e., {}) in console.log, the log will show the object names as well.

console.table():

Limiting column names:
  • By default, console.table() lists all elements in each row. You can use the optional columns parameter to select a subset of columns to display.
  • In the example below, I am displaying only ‘Name’ and ‘Email’ columns.The console.table() static method displays tabular data as a table.

console.assert():

  • Lets say you want to log a message only if a certain condition is false. You can use the console.assert()
  • In the below example, I have a control with ‘id’ demo but not demo1. So only the second console.assert logged the message as the check for demo1 failed.

console.count():

  • The count() method counts the number of times console.count() is called.
  • 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.

console.trace():

  • The console.trace() method displays a trace that show how the code ended up at a certain point.
  • Its helpful to identify from which line and which function we got the error from.
  • In below example, trace logs the line number as 7.

console.time() and console.timeEnd():

  • The time() method allows you to time code for testing purposes.
  • The timeEnd() method ends a timer, and writes the result to the console.

console.group() and console.groupCollapsed() and console.groupEnd():

  • The group() method starts a message group. All new messages will be written inside this group.
  • The groupCollapsed() method starts a collapsed message group.
  • The groupEnd() ends a message group.

Apply css styling to the log:

  • Use %c in the console.log() to apply styling, as shown below.

Refer this document for more console methods.

🙂

Advertisements
Advertisements

One response to “JavaScript | Useful ‘Console’ functions”

  1. Power Pages DevTools extension | Rajeev Pentyala - Microsoft Power Platform Avatar

    […] how we use console.log to capture logs, Developers can now add log statements in […]

Leave a comment