Console Dot Log
Tags: javascript, tutorial, debug, beginners
Published: 2020-04-23 00:07:18

# console

My personal favorite all-around utility for reading errors, checking variables, counting re-renders, saying hello to the world, and everything in between! `console.log()` has always been my best buddy wherever I go, but I also know that it can do so much more! Like with any tool, there are specific ones for specific jobs.

In this article, I will walk through the various other functions that you can run with `console` and some practical uses for each. Feel free to open up your web console and follow along. 

## Logging

Oh wow, did you know that you can log stuff to the console? Yes, we all know that you can log stuff to the console, but I'm sure everyone has their specific styles for logging. Personally, I prefer typing the variable name with a colon, then the variable.
```
console.log('Variable Name: ', variable)
// output: Variable Name: variable
```
Otherwise, if you need to log multiple variables it's much faster to just output an object.

```
const first = "Kaemon", last = "lovendahl"
console.log({ first, last })
// output: { first: 'Kaemon', last: 'lovendahl' }
```



## Logging Objects

There are so many ways you can log objects to the console. `console.log()` is great, but have you tried `console.dir()` or `console.table()`?

`console.dir()` shows objects similarly to when you log them. The only difference is that they are logged already expanded.

`console.table()` displays a table of all the key/value pairs within the object. Keys or "index" is displayed on the left, and values on the right.
```
const fireball = { damage: '8d6', duration: 'instantaneous', level: 3, castable: true }
console.table(fireball)
```
output:

|(index)|Values|
|:-----|:-----|
|damage|8d6|
|duration|instantaneous|
|level|3|
|castable|true|

 You can also use `console.table()` with an array of objects. It's legit!



## Substitutions

`Console.log()` can use substitution strings to log things even faster!
```
console.log("I cast %s at the goblin!", "fireball")
// output: "I cast fireball at the goblin!"
```
You can do this with:
* Strings - `%s`
* Objects - `%o` or `%O`
* Integers - `%d` or `%i`
* Floating-point values - `%f`

You can even specify the decimal places with `%d`, `%i`, and `%f` by adding `.num` for the decimal places. Using this with `%d` and `%i` will add leading zeros. Using it with `%f` will add determine the decimal places we show.
```
console.log("More enemies will arrive in %.2d turns.", 5)
// output: More enemies will arrive in 05 turns.
```
Substitutions are a great way to quickly type out logs that include multiple variables.



## Counting

Ever used `console.log()` to count the variables in a loop, or to see how many times a function was being called? The console has a better tool for that! Introducing `console.count()` and `console.countReset()`.

`console.count()` will start at one, and increment every time its called. You can add a string for a label, or leave it blank and it will log as default. Once you're done counting you can call `console.countReset()` to set it back to zero.

Just remember that if you used a label with `count()` then you must also use it with `countReset()`

```
for (let i = 0; i < 100; i++) {
  console.count("In the loop")
}
console.countReset("In the loop")

// output: In the loop: 1 - 100
// and back to 0.
```



## Assertions

Ever get frustrated with a truthy or falsey value not working as expected? Have you ever wanted to log something if it's specifically true OR false?

ASSERTIONS!

`console.assert()` takes a truthy/falsey value as it's first param and either a list of objects or a substitution string as the second param. `console.assert()` will log an error level message containing your second param and a stacktrace if the assertion is falsey. Otherwise, it does nothing.

```
const sightCheck = 5 // you notice nothing unusual about your surroundings
console.assert(sightCheck >= 15, 'You take %d damage from a thief that was hiding in the bushes', 15)
// output: Assertion failed: You take 15 damage from a thief that was hiding in the bushes
```



## Log Levels

Just as we log messages with `console.log()`, there are other log levels that can be used for even greater specificity.

* debug - looks similar to log
* info - has a little "i" with a circle
* warn - Yellow text warning message
* error - Red text error message and includes a stacktrace

No longer should you use `console.log('Error: ', error)` You should now use `console.error(error)`!




## Timer

Ever had a function that took a lot longer to finish than you expected? Ever had a hard time finding out which part of it was so time-consuming? Enter, `console.time()`, `console.timeLog()`, and `console.timeEnd()`.

Similar to `console.count()` this method takes a label as an argument to identify the timer. According to [MDN web docs](https://developer.mozilla.org/en-US/docs/Web/API/Console/time) you can have up to 10,000 times running on a single page!

`console.time()` starts a timer while calling `console.timeLog()` logs the time. Once you want to stop the timer just call `console.timeEnd()`.

```
const getTheRelic = () => {
  console.time("Epic Quest")

  getMap()
  console.timeLog("Epic Quest")

  bribeGuards("3 gold")
  console.timeLog("Epic Quest")

  parseRunes("....")
  console.timeLog("Epic Quest")

  console.timeEnd("Epic Quest")
}
```

This example starts a timer with the label "Epic Quest". We then log the time after each step and in the end, we stop the timer. Checking the logs will reveal which function call is taking so long.



## Trace

This method is quite simple. Call `console.trace()` to view the stack trace from where it was called. Great for figuring out what's happening when you have a bunch of function calls!



## Groups

Ever have a bunch of logging statements when trying to pin down a bug? It can get pretty confusing when the logs are getting called out of order, and multiple times!

`console.group()` helps you to sort out your logs into convenient... GROUPS!
Start out your logging with `console.group()` and any logs after it will be placed in its group. Then, after you have your logs grouped together you can call `console.groupEnd()` to signify the end of the group.

```
console.group("Gold")
console.log("30 Gold Pieces")
console.log("20 Ruby Gems")
console.groupEnd("Gold")

// Output:
Gold
  30 Gold Pieces
  20 Ruby Gems
```

Also, instead of `console.group()` you can call `console.groupCollapsed()` to automatically collapse the group when it's logged.



## Styling

Last but not least, you can even style your logs! This would be a great idea to make custom admin or development logging! Things like logging custom events, errors, or even a fun easter egg that others can see!

Similar to substitutions you can apply CSS styles to logs by adding `%c` to your message in the first param and declaring your styles within a CSS string for the second param. Any text after the `%c` will have the styles applied.

```
// Try copy/pasting this log to your console!
console.log("%cFIREBALL", "background: linear-gradient(orange, red); color: black; font-weight: bold; font-size: 3rem; padding: 1rem;")
```

Check [this link](https://developer.mozilla.org/en-US/docs/Web/API/console) out for a full list of styles that can be applied!

## The End

Thank you for making it all the way through this article! I hope you learned something new or got a good refresher on everything we can do with the console.