Methods to Format Console Output in JavaScript – CloudSavvy IT

Posted on


Illustration showing JavaScript console log statements

JavaScript builders are acquainted with the standard console.log() perform. Though console logging might seem easy, there’s far more out there inside the console object. Let’s take a look at how one can improve your log messages with superior formatting.

The Fundamentals

Let’s recap the most-used console capabilities:

  • console.log(knowledge, ...args) – Logs knowledge to the console. Some other arguments handed can even be emitted on the identical line.
  • console.information(knowledge, ...args) – Equal to console.log() however usually with emphasised formatting – Chrome, for instance, provides a blue background and an data “i” icon.
  • console.error(knowledge ...args) – The identical as console.log(), besides the output is directed to the stderr (error) stream. Most browsers routinely format the output with a crimson background to convey that an error occurred.
  • console.warn(knowledge, ...args) – The identical as console.error(), besides a yellow background is generally utilized to point the much less extreme warning standing.

Format Specifiers

Builders often solely go a single argument to the above instructions. Nonetheless, all of them settle for a number of arguments, that are routinely concatenated within the remaining output.

You may as well use arguments with printf-compatible format specifiers outlined by a string in knowledge:

const worth = 10;
const out there = "out there";
console.log("There are %d choices", worth, out there);
// Logs "There are 10 choices out there"

The out there format specifiers are as follows:

  • %s – Format as a string.
  • %i – Format as an integer.
  • %f – Format as a floating level worth.
  • %O – Format as a JavaScript object.
  • %o – Format as a DOM component.
  • %c – Format as a CSS rule, which is utilized to the emitted log line.

Help for the final two varies by JavaScript engine. They’re out there in fashionable browsers however not essentially in different execution contexts.

Including Photographs

Utilizing the CSS format specifier, it’s potential to incorporate photos in console output! This works in browsers however gained’t be supported in CLI environments similar to Node.js.

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

We hijack CSS’ background-image rule to render the picture. Whereas it could appear lighthearted, this might have sensible use circumstances in case your debugging includes working with photos. You’ll be able to examine the pictures being retrieved with out truly emitting them to the web page.

Tabulated Output

JavaScript contains built-in assist for emitting tabulated knowledge to the console. Use console.desk() with an array of uniform objects. The column headers can be decided routinely, primarily based on the properties widespread to every object.

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

This may be extraordinarily helpful once you’re working with objects in bulk. As a substitute of getting to iterate an array and name console.log() with every merchandise, simply use console.desk() and profit from the routinely formatted output.

Conditional Output

You should use the console.assert() perform to situation output on the worth of an expression. This reduces the code you want to write in contrast with prefacing a console.log() with an if assertion.

Your message will solely be logged if the expression evaluates to false. An expression evaluting to true will end in nothing being emitted.

console.assert(true, "I by no means seem");
 
console.assert(false, "I can be logged");

The console.assert() perform doesn’t have an effect on runtime. No error can be thrown if the assertion fails; your expression is used solely to find out whether or not to log to the console.

Message Teams

You’ll be able to visually group sections of output along with console.group(). This may apply an automated indent to subsequent strains utilizing a predefined variety of areas.

To shut the group, name console.groupEnd(). This restores the earlier indentation.

You might name console.group() a number of occasions earlier than console.groupEnd() to create deeply nested output. console.groupEnd() reverts the indentation by one step at a time, so that you’ll must match the variety of group() and groupEnd() calls earlier than you get again to the default degree.

Counters

Use console.rely(label) to create an inside counter with a given identify:

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

This offers you an easy strategy to emit incrementing values. You don’t need to specify a reputation – the default counter can be used routinely. You’ll be able to reset counters to 0 utilizing console.countReset(label).

Timers

The console has built-in assist for operation timing. Elapsed time is measured in milliseconds and emitted in seconds (e.g. “1.234s”); it’s not assured to be high-accuracy.

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

Timers assist elective labels in the identical method as counters. This allows you to handle a number of timers concurrently when timing completely different points of your code.

Utility Strategies

The console object contains a number of utility strategies which assist you handle your output.

  • console.clear() – Clears the console of all seen output. The consequences will differ by execution surroundings.
  • console.dir(obj, choices) – Emits an inventory of all of the enumerable property/worth pairs of the item obj. You’ll be able to customise the recursion depth utilizing the depth property of the choices object.
  • console.hint() – Emits a stack hint to the present level in your code, enabling easy debugging of the execution path taken.

There are different non-standardised strategies that are engine-dependent. An instance is console.profile(), which is broadly out there however with differing implementations. In browsers, it typically invokes high-accuracy profiling that can assist you diagnose efficiency points.

Conclusion

There’s far more to JavaScript’s console than the fundamental console.log()! Taking the time to be taught the out there capabilities can drastically speed up debugging, significantly when working with advanced objects or fast-moving output.

The out there options do depend upon the JavaScript engine you’re working with. Usually, you’ll get essentially the most superior styling from an up-to-date browser, though Node.js additionally helps many of the strategies we’ve described right here.



Source link

Gravatar Image
I love to share everything with you

Leave a Reply

Your email address will not be published. Required fields are marked *