What is Console?

What is Console?

and what are 10+ most useful methods ✨

In this article, you will learn about the console and its methods, with examples of how to use them.

🚀 Console

A web console is primarily used to log information associated with a web page, such as network requests, JavaScript security errors, warnings, CSS, etc. It enables us to interact with a web page by executing a JavaScript expression in the contents of the page.

Console in JavaScript is an object that provides access to the browser's web console. It can be coupled with other methods to achieve a variety of actions, which are used for debugging and results logging.

The console is a global object that is accessible via the global scope of the browser window. You can use it as console or a window console.

console.log() is one of the best friends in a web developer's life; it makes our lives so much simpler. But did you know console consists of more than just console.log()? There are a lot more methods that can help you debug your code even better. Let's take a look at some of them:

🚀 Shortcuts to open the console in browsers

All modern browsers have a console that can be opened using a shortcut key from the keyboard. To open up the browser console:

  • Use the F12 key in Chrome and other chromium-based browsers.
  • Use CTRL + SHIFT + K keyboard shortcut keys for Mozilla.
  • Use Option + ⌘ + C keyboard shortcut keys in Safari (if the developer menu does not appear, then open Preferences by pressing ⌘ +, and in the Advanced tab check “Show Develop menu in menu bar”).

It can also be opened by right-clicking on a web page and selecting the “Inspect” option from the menu.

🚀 Its Methods

✨console.log( )

To log output to the console. We can use any type within log(), such as a string, array, or object.

console.log('You Got This')
console.log(800)
console.log(true)
console.log(null) 
console.log(undefined)
console.log({a:1, b:2}) //object 
console.log([1,2,3,4]) //array

console.log() examples

✨console.dir( )

Prints a JSON representation of the specified object.

let info = {
"name": "Habiba",
"Social": "@habibawael02"
}
console.dir(info)

console.dir() example

✨console.dirxml( )

Displays an XML/HTML Element representation of the specified object if possible or the JavaScript Object view if it is not possible.

let info = {
"name": "Habiba",
"Social": "@habibawael02"
}
console.dirxml(info)

console.dirxml() example

✨console.clear( )

To clear the console. This console will be cleared, in the case of Chromium-based browsers, a simple overlayed text will be printed like the one shown in the screenshot below stating ' Console was cleared', while in Firefox, no message is returned.

console.clear()

console.clear( )

✨console.warn( )

Used to log warning messages to the console. By default, the warning message will be highlighted with yellow color.

console.warn('This is a warning')

console.warn( )

✨console.error( )

This method is used to log error messages to the console. useful in testing code. By default, the error message will be highlighted in red color.

console.error('This is an error')

console.error( )

✨console.assert( )

Log a message and stack trace to the console if the first argument is false.

const isEven = n => n % 2 === 0;
for (let i = 0; i < 3; i++) {
    console.assert(isEven(i), '%s is not even!', i);
}

console.assert( )

✨console.trace( )

When you are working with a lot of nested function calls or recursion at some point you will need to know which function called who. console.trace() is a handy way to do that.

const shallow = () => deep();
const deep = () => deeper();
const deeper = () => deepest();
const deepest = () => console.trace()
shallow()

This will log this stack trace console.trace( ) Now we can easily see that shallow called deep, which called deeper which called deepest.

✨console.count( )

To output, the number of times a line of code has been executed under a given label.

for(let i=0; i<5; i++){
    console.count('This is number', i)
}

console.count( )

✨console.table( )

This method is very useful when displaying arrays of objects, as it makes the output very readable.

let students = [
{
name: 'Habiba',
age: 21
},
{
name: 'Peter',
age: 20
},
{
name: 'Daniel',
age: 22
},
];
console.table(students);

console.table( )

✨console.group() and friends

You can use nested groups to help organize your output by visually combining related material. To create a nested block, call console.group(). console.groupCollapsed() creates a new inline group, indenting all following output by another level. However, unlike group() this starts with the inline group collapsed requiring the use of a disclosure button to expand it. To move back out a level (Exits the current inline group), call groupEnd().

console.group('label')
console.log('This is a sample group log')
console.warn('This is a sample group warning')
console.error('This is a sample group error')
console.groupEnd('This is a sample group');
console.log('This is a new section');
console.groupCollapsed('label')
console.log('This is a new section');
console.groupEnd('This is a sample group');

console.group() and friends

✨console.time() and friends

The console object also has timer methods that allow you to calculate the duration of a specific operation. To start a timer, call the console.time() method, giving it a unique name/label as the only parameter. Up to 10,000 simultaneous timers can run on a given page. To check the current value of the timer, call the console.timeLog() method, giving the label of the timer which was started. This will output the time, in milliseconds, that has elapsed since the timer started. And finally, you can stop the timer by calling console.timeEnd(), again using the same label. This will also output the elapsed time, in milliseconds.

console.time("answer time");
console.log("Hey");
console.timeLog("answer time");
console.log("You got this");
console.timeEnd("answer time");

console.time() and friends

🚀HTML elements in the console

console.log(document.body)

HTML elements

🚀console.memory

The memory property can be used to check out the heap size status. Note: memory is a property and not a method.

console.memory

console.memory

🚀Styling console output

Users can add styling to the console logs in order to make logs custom. You can use the %c directive to apply a CSS style to console output

console.log("%cText color is red and increased font size", "color: red; font-size: 2rem;")

Styling

We can add %c multiple times.

console.log("Multiple styles: %cred %corange", "color: red", "color: orange", "Additional unformatted message");

multiple styling

🚀Conclusion

Thank you for your time. I hope you found it useful. ❤️

If you found this post helpful, Don't forget to give ❤️ and follow me on Twitter or over here to stay updated on my blog posts!

If you have any suggestions or tips, feel free to comment below or contact me on Twitter at @habibawael02. See you later!