Discover more Console methods available in JavaScript and learn how to style them

Discover more Console methods available in JavaScript and learn how to style them
Check out my Github for my free-to-read JavaScript Ebook that covers all the new features from ES6 to 2019. If you want find a great place for interactive tutorials, i recommend Educative where I'm currently finishing to build my JavaScript course.
This website contains affiliate links. See my disclosure about affiliate links here

One of the first things that new JavaScript programmers learn is how to use console.log to print their statements and view the output of their code.

While an undoubtedly useful thing to know, the console Object actually has many more methods available to use and in this article, we are going to look over a few of the more interesting ones.

console.log()

Let's just have a quick review of this one. As the name implies, it is used for logging values, whether they are primitives such as string or number or the result of a function.

console.log(5);
// 5
const sayHello = () => {
    return 'hello'
}
console.log(sayHello());
// hello

console.info()

In substance, it's the same as console.log(), it differs only in the meaning and to provide a degree of separation between informative logs and debug logs. You may want to keep console.info() in your code but probably you want to get rid of all your console.log() before pushing it as they were added while debugging.

In Firefox, a little 'i' icon is displayed to show that it's a console.info output.

console.warn()

console.warn() is used to output a warning to the console and in Firefox a little yellow warning icon will be displayed alongside the output message.

console.warn image

console.error()

This one is used to log errors to the console, in Firefox a red warning icon is displayed alongside the output message while in Chrome it will display a white cross inside of a red circle.

The difference with the previous ones is that in this case a stack trace will also be logged, allowing you to see where the error comes from.

function sayHello() {
    console.error('Error!!!')
}

sayHello()

console.error image

console.trace()

If you want to know the stack trace of a method even when there's no error, then you should use the method console.trace().

const func = () => {
    const nestedFunction = () => {
        console.trace()
    };
    nestedFunction()
}

func()

console.trace image

As you can see this logged the stack trace of our method and since it's not an error, it's not displayed in red.

console.time(), timeEnd(), timeLog()

With console.time() you can start a timer to track how long an operation takes.

You can give the timer a unique name and then call console.timeEnd(nameOfYourTimer) to stop it and log the duration to the console.

console.time('countToTen');

setTimeout(function(){
    console.timeEnd('countToTen')
},10000)

// countToTen: 10000.5087890625ms

After 10 seconds you will see the timer logged in the console, this can be useful if you want to monitor the performance of your methods.

You can have up to 10,000 unique timers at the same time so create as many as you need.

If you only want to log the current timer but you don't want to stop it yet, use the method console.timeLog() with the name of your timer and it will be logged in the console without stopping it.

This can be useful if you are monitoring different blocks of a method and you want to see where the performance issue may be located.

console.dir(), dirxml()

console.dir() prints an interactive list of properties of your object. Nowadays, browsers like Chrome and Firefox display interactive objects even when using console.log() so the need to use this is limited.

console.dirxml() prints an interactive tree markup of a DOM element, so for example if you were to run console.dirxml(console.body); on this very page you would see an interactive tree of all the DOM elements inside of the body of this page.

console.assert()

This method is used to run an assertion. If the first argument fails the subsequent arguments are printed to the console.

console.assert(1 > 2, '1 is not more than 2');
// Assertion failed: 1 is not more than 2
console.assert(1 < 2,' 1 is less than 2');
// nothing is printed

The first line logged to the console our custom message '1 is not more than 2' along with a stack trace.

The second console.assert() did not print anything because the assertion did not fail. You can't set a message to be printed when the assertion succeeds, only when it fails.

console.clear()

As the name implies, this method is used to clear the console, simple and easy. Every browser has a dedicated button and shortcuts to clear the console so you'll probably rarely use this method but it's worth knowing that it exists.

Now that you know how to use more methods than just console.log(), let's have a look at how to style them to make them more recognizable.

It is actually very simple to style your messages and you can do it this way:

console.log("%cThis is red", "color:red");

We prepended '%c' before the string where we want to apply some styling and we added a second argument to the method to apply some CSS styles to it.

You are not limited to colors, you can apply any type of font styling you want such as font-weight, font-family, etc... using the same syntax you would use for CSS, separating each style with a semicolon.

console.log("%cThis is red", "color:red; font-size:30px");

This wraps up this intro to the console API methods for JavaScript if you want to learn all of them you can head over to MDN and have a look at the one I didn't mention here.


Thank you very much for reading, if you enjoyed this article, please share it with friends and colleagues and if there is a topic you would like me to cover, reach out to me on twitter at @montalesi. Follow me on DevTo or on Twitter for more.

complete guide to modern javascript alberto montalesi ebook bannerGet my ebook on Amazon and Leanpub or get my course on Educative


NEWEST ARTICLES




ABOUT ME

author alberto montalesi profile picture

Alberto is a software developer specialized in building enterpise software using Angular and author of the 'Complete guide to Modern JavaScript' ebook and course. In his free time he writes articles and tutorials on InspiredWebDev.com and Dev.to

You can read more about him here