قالب وردپرس درنا توس
Home / Tips and Tricks / Ways to Format Console Output in JavaScript – CloudSavvy IT

Ways to Format Console Output in JavaScript – CloudSavvy IT



Illustration with JavaScript console log instructions

JavaScript developers are familiar with the modest console.log() position. While logging may seem simple on the console, there is a lot more available in it console object. Let’s take a look at how to improve your log messages with advanced formatting.

The base

Let’s summarize the most commonly used console features:

  • console.log(data, ...args) ̵
    1; Logs data to the console. All other arguments passed are also sent on the same line.
  • console.info(data, ...args) – Equal to console.log() but normally with emphasis on formatting – Chrome adds a blue background and an information i icon, for example.
  • console.error(data ...args) – The same as console.log()except that the output to the stderr (error) stream. Most browsers automatically format the output with a red background to indicate that an error has occurred.
  • console.warn(data, ...args) – The same as console.error(), except that a yellow background is normally applied to indicate the less severe alert status.

Format specifications

Developers usually only pass one argument to the above commands. Nevertheless, they all accept multiple arguments, which are automatically merged in the final output.

You can also use arguments with printf-compatible format specifications defined by a string in data:

const value = 10;
const available = "available";
console.log("There are %d options", value, available);
// Logs "There are 10 options available"

The available format specifications are as follows:

  • %s – Format as a string.
  • %i – Format as an integer.
  • %f – Format as a floating point value.
  • %O – Format as a JavaScript object.
  • %o – Format as a DOM element.
  • %c – Format as a CSS rule, which is applied to the broadcast log rule.

Support for the latter two varies by JavaScript engine. They are available in modern browsers, but not necessarily in other execution contexts.

Add images

Using the CSS format specification it is possible to include images in console output! This works in browsers but is not supported in CLI environments such as Node.js.

const css = [
    "background-image: url(https://example.com)",
    "background-size: cover",
    "height: 100px",
    "padding: 15px",
    "width: 100px"
];
console.log("%cI'm An Image!", css.join(";"));

We hijack CSS ‘ background-image line to display the image. While it may seem light-hearted, it can have practical uses if you’re working with images when debugging. You can check the retrieved images without actually sending them to the page.

Tabular output

JavaScript has built-in support for sending data in tables to the console. Use console.table() with a series of uniform objects. The column headings are automatically determined based on the properties that apply to each object.

const objects = [{a: 1, x: "a"}, {a: 2, x: "b"}];
console.table(objects);

This can be very useful when working with large numbers of objects. Rather than having to iterate over an array and console.log() use with each item console.table() and take advantage of the automatically formatted output.

Conditional output

You can use the console.assert() function to condition the output to the value of an expression. This reduces the code you need to write compared to pre-entering one console.log() Right away if statement.

Your message is logged only if the expression results in false. An expression that refers to true will result in nothing being emitted.

console.assert(true, "I never appear");
 
console.assert(false, "I will be logged");

The console.assert() function does not affect runtime. No error is thrown if the assertion fails; your expression is used only to determine whether you want to log in to the console.

Message groups

You can visually group sections of output with console.group(). Automatically indents subsequent lines with a predefined number of spaces.

Call to join the group console.groupEnd(). This restores the previous indent.

You may call console.group() several times before console.groupEnd() to create deeply nested output. console.groupEnd() returns the indent step by step, so you must enter the number group() and groupEnd() before returning to the default level.

Counters

Use console.count(label) to create an internal counter with a specific name:

console.count("my-counter");
// my-counter: 1
console.count("my-counter");
// my-counter: 2

This gives you an easy way to broadcast incremental values. You don’t have to provide a name – it default counter is used automatically. You can reset counters to 0 with console.countReset(label).

Timers

The console has built-in support for control timing. The elapsed time is measured in milliseconds and broadcast in seconds (eg “1.234s”); high accuracy is not guaranteed.

console.time();
// ...some time later...
console.timeEnd();
// Emits the elapsed time ("1.234s")

Timers support optional labels in the same way as counters. It allows you to manage multiple timers at the same time when timing different aspects of your code.

Utilities

The console object contains several utility methods to help you manage your output.

  • console.clear() – Clears the console from all visible output. The effects differ per implementation environment.
  • console.dir(obj, options) – Displays a list of all enumerated property / value pairs of the object obj. You can adjust the recursion depth with the depth owned by the options object.
  • console.trace() – Broadcasts a stack trace to the current point in your code, allowing easy debugging of the execution path taken.

There are other non-standardized methods that are motor dependent. An example is console.profile(), which is widely available, but with different implementations. In browsers, it generally invokes very accurate profiling to help you diagnose performance issues.

Conclusion

There’s a lot more to the JavaScript console than the basics console.log()! Taking the time to learn the available functions can dramatically speed up debugging, especially when working with complex objects or fast-moving output.

The available functions depend on the JavaScript engine you are working with. Overall, you get the most advanced style of an up-to-date browser, although Node.js also supports most of the techniques we’ve described here.


Source link