The JavaScript console is a useful tool when developing front-end or server-side applications. In this post, I'll be going over 5 features of the console which I hoped I knew earlier.
YouTube Video
I've created a video detailing these features on my YouTube channel, dcode.
If you enjoy, subscribe and check out my other 500+ videos on programming and web development 🙂
1. Console Groups
With the console.group()
function, you can create collapsible groups in the console to group and name your output.
Code
console.group("Person Data");
console.log("Name: Dom");
console.log("Age: 32");
console.groupEnd();
console.log("Outside of the group...");
Output
2. Live Expressions
Available in the Google Chrome Developer Console is the Live Expression feature, which allows you to input a JavaScript expression and receive live updates on it's value.
These are great for keeping track of variables as you debug, such as X, Y values or the state of the application.
How To Use
3. Timing Your Code
With the console.time()
function, you're able to benchmark and time your code. For example, the code below will output how long it took to add 10,000 <h5>
tags to the page.
Code
console.time("addHeadings");
for (let i = 0; i < 10000; i++) {
document.body.insertAdjacentHTML("beforeend", "<h5>Heading</h5>");
}
console.timeEnd("addHeadings");
Output
4. Styling With CSS
Yes, you heard that right. You can use CSS in the JavaScript console. Using the console.log()
function and multiple arguments, you can add CSS rules to the text.
By using %c
in your string, you are saying that any text after it will have the subsequent CSS styles applied.
Code
console.log("I am regular and %cI am boldy blue.", "color: blue; font-weight: bold;");
Output
5. Assertions
With the console.assert()
function, you can test if your code is doing what you expect it to do, similar to unit tests. If the given expression isn't true
, an exception will be thrown.
While the usefulness of this feature is going to vary from developer to developer, it can be used in place of console.log()
in many scenarios.
Code
console.assert(true === true);
console.assert(true === false);
Output
dcode 📷
If you want to strengthen your web development skills and listen to my voice all day, I recommend taking a look at my YouTube channel, dcode.
I've got hundreds of videos on HTML, CSS & JavaScript which you might enjoy - if you do, consider subscribing! 🧐
Top comments (1)
Nice article! How could you not include
console.table
though?!