Better Debugging Output: The Console.Assert Way!
Tags: javascript, debugging, codequality
Published: 2022-04-13 13:24:23

---
title: Better Debugging Output: The Console.Assert Way!
published: true
description: The JS Console is a bug's worst enemy
tags: JS, Javascript, Debugging, Quality
series: Better Console Driven Debugging
cover_image: https://images.unsplash.com/photo-1607472586893-edb57bdc0e39?ixlib=rb-1.2.1&ixid=MnwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8&auto=format&fit=crop&w=1374&q=80
---
#Debuggers?  In MY Console?
Using the console to debug applications [seems](https://medium.com/@benlmsc/stop-using-console-log-d281a900dedb) [to](https://dev.to/dogealgo/why-you-should-not-use-console-log-for-debugging-4pgg) [make](https://daily.dev/blog/stop-using-console-log) [people](https://medium.datadriveninvestor.com/stopping-using-console-log-and-start-using-your-browsers-debugger-62bc893d93ff) [big](https://dev.to/songthamtung/stop-console-logging-this-is-how-to-use-chrome-to-debug-javascript-48nm) [mad](https://codesource.io/debugging-your-javascript-code-console-log-vs-debugger/).

The thing I find objectionable about the "Don't use Console!" story is summed up in this quote:

> many developers regularly use the console object’s log method in a way that _I think is incorrect_.

See, the thing is, despite having (and perhaps one day sharing) rebuttals for many of the admittedly well made points, the truth is that _I simply don't care if you think I'm wrong and ultimately you can't stop me._

I _like_ using console debugging despite knowing of "Better" solutions.  This series is going to explore features of the JS Console I don't see as often as the venerable `console.log()`, in the hopes that you'll like it too.  This time, we're making our logging less verbose, with `console.assert()`.

# Console.assert
## Console.assert?
Yes!

You call `console.assert()` with a boolean condition and a message; The message is only output if the condition evaluates to false.

```JS
console.assert(someMsg.includes("All is Well"), "There has been An Incident.")

// someMsg = "Calamity! Perfidy! Tragedy!"
// Output: 
Assertion failed: There has been An Incident.
```
## Why is this better?
Logging can give us different _kinds_ of information.  Some log data is *structural* and lets us know _what code_ is executing.

Some log data is *operational* and lets us know _what data_ is being executed on.

Typically, I want all structural log data when I'm debugging, so I can fully trace my application flow.  Contrariwise, I only want operational data that relates to the error I'm tracking down.  If an error-like condition hasn't occurred, operational log data often doesn't tell me anything.

## The Beauty of Asserting False
I usually only want output if the _expected_ behaviour doesn't happen, so semantically, this makes sense.  I tell the JS engine what I want, and it only alerts me if it doesn't happen.  Mentally, I only have to think about what "correct" looks like, not what might be "incorrect".

# Make the output better
## Auto-append object values
Another `console.assert` option is to pass a condition and an array of objects.  If the condition is false, the objects are stringified, appended together and output.  This can save you writing a custom error message, which is 🧑🏼‍🍳💋.

```JS
let good_investments = ["Mines", "Urchins", "New Fangled Electricity"]
let bad_investments = ["Radium Health Tonics"]

console.assert(bad_investments.length == 0, bad_investments);

// Output:
Assertion failed: Radium Health Tonics
```

## Output Formatting
What if we want something _more_ then just a set of object values?  We could pre-format a message string, _or_.... We could use [string substitutions](https://developer.mozilla.org/en-US/docs/Web/API/console#outputting_text_to_the_console) to do it inline!

```JS
let good_investments = ["Mines", "Urchins", "New Fangled Electricity"]
let bad_investment = "Radium Health Tonics"

let losses = {
	pounds: 150,
	reputation: 47,
	body_parts: ["Teeth", "Jaw"]
}

console.assert(
	bad_investment.length == 0,
	"%s has cost you %d Pounds and reduced your reputation by %f%",
	bad_investment,
	losses.pounds,
	losses.reputation
)

//Output:
Assertion failed: Radium Health Tonics has cost you 150 Pounds and reduced your reputation by 47%
```
If you're confused about what's happening here, check out my rapid guide to the [Console method string substitutions](https://dev.to/dylanlacey/cool-console-stuff-easy-object-inspection-14c4).

## Object String Substitution (My favourite bit)
In fact, that same article shows off Object substitution, which is _extremely_ useful here.  Instead of:
```
Assertion failed: [object Object]
```
Object substitution lets `console.append` return a nicely formatted message to the CLI... and an _expandable, clickable_ Object in the browser console!  Click it, and you'll go directly to the inspector to dig around and see what's gone wrong.

```JS
console.assert(
	false, 
	"Your %O exceed %d pounds. See %o.", 
	losses,
	losses.pounds,
	losses.history
)

//Output:
Assertion failed: Your >Losses exceed 150 pounds. See >History.
```

# Wrap-up
So that's the power of `console.assert`!  Rich, compact debugging messages that show up only when needed, giving you ample ability to present and explore the relevant information.

If you liked this, please hit the Dopamine (❤️) Switches (🦄) on the left, and subscribe to my writing for the next entry in the JS Console Debugging series!

# Recognition
Header image is by [@Sigmund](https://unsplash.com/@sigmund), used under the Unsplash License.