I used to use the console.log a lot. I still do, but I used to, too. However, my usage of the console.log has changed quite a bit over the years as I became more familiar with it.
View This On YouTube
If you have ever used the console.log to validate or view your Javascript, you may be familiar with the following:
var width = 100
var height = 100
console.log(width)
console.log(height)
// this will produce 100 and 100 in your console
...but it can do so much more than just printing variables. Let's dive into how to properly use more advanced features within your console.log.
Show Name Value Pairs
Using the example above, you can see it does not give you a lot of information. It prints what you tell it to, but if you are working with dozens of variables, you may not know what each value represents. This is where name-value pairs come in. Try the same code above but with it as an object.
console.log({width})
console.log({height})
// this will produce {width: 100} and {height:100} so it is more easy to read
console.log({width}, {height})
// this will produce an object containing your objects: {width: 100} {height: 100}
Specific Console Messages
Sometimes, you need to show a specific type of console message. You may need to just display data or you may need to record a visual error message. This is pretty easy to accomplish just by changing what type of console you are using.
console.log("This is a message") //standard display
console.info("This is information") // another way to do a standard display
console.error("This is an error message") // highlight the message in red and flag it as an error
console.warn("This is a warning") // highlight the message in orange and flag it as a warning
This will help you keep track of how you are using your messages. You can easily look at the console log and see what may be potentially breaking your application. The colors really help you wrap your head around how your application is interacting with your JavaScript code.
Errors and Assertions
The console.assert() method writes an error message to the console if the assertion is false. If the assertion is true, nothing happens. This can help you quickly troubleshoot true vs false and display specific error messages when your assertions do not happen as expected.
function test(message) {
if(!message) {
// if no variable has been added, it will fail and show a console error message
console.error("Message is not defined")
}else{
console.assert(
// the backticks are important for the message display since this assertions takes the input and displays it back to the script
message.length >= 5, `"${message} is not over 5 characters"`
)
}
}
test() // will fail since there is no message
test('msg') // will fail since the message is less than 5 characters
test('message') // will pass and not display a message
Trace
One of my favorite console abilities is the trace function. This function allows you to see what functions or methods were used to get to where you are. This is especially helpful when you are troubleshooting your code. You can add a trace in the function that is breaking to see how it got there to find out what is missing.
function one(){
// call our second dummy function
two()
}
function two(){
// write a trace here to see that this function was called from function one()
console.trace()
}
// call our initial function that then calls our trace function
one()
Grouping
Grouping can be helpful if you want to see your console.log grouped by specific preset sections. You can even collapse certain sections if needed to make it cleaner. They can always be expanded if needed but you can show one section at a time if you like.
//create our group objects
let groups = {
"Group One": ['One', 'Two', 'Three'],
"Group Two": ['Four', 'Five']
}
//loop through our groups automatically using JavaScript
for (group in groups){
console.group(group)
groups[group].forEach(g => console.log(g))
console.groupEnd(group)
}
// loop through our groups manually
console.group('Group One')
console.log('One')
console.log('Two')
console.log('Three')
// collapse all groups within the Collapsed name
console.groupCollapsed('Collapsed')
console.log('Four')
console.log('Five')
// end our groups
console.groupEnd('Collapsed')
console.groupEnd('Group One')
Tables
Another really cool thing you can do with the console is tables. This gives you the ability to write tabular data to the console so you can view it as it would be as an HTML table. Also, keep in mind that you can copy the tabular data and paste it into Excel and it will keep its structure. This is a pretty neat trick if you want to see how your data is rendered and how you can control that rendered data.
// define our tabluar objects
let tables = {
1: {name: 'Test 1', email: 'test1@example.com', phone:'123-456-7890'},
2: {name: 'Test 2', email: 'test2@example.com',phone:'123-456-7890'},
3: {name: 'Test 3', email: 'test3@example.com',phone:'123-456-7890'}
}
// display the entire table
console.table(tables)
// display only the name and email objects from our table data
console.table(tables,['name', 'email'])
With the previous console.log functions, you can view and manipulate your JavaScript data easily in the browser. You can create and modify your types of messages and create traces for you to troubleshoot better.
Debugger
So, having said that, there is a function we can use that can work with all of this and give you a pausable interface that allows you to set break points and skip or go into those breakpoints. This is the JavaScript function debugger. It is easy to set up and use and will help you debug your code the same way you do within VS Code if you use a debugger.
debugger
That's it. Run that code before your other code to run through the browser's debugger interface as if you are debugging server-side code. It took me way too long to learn this simple command but it is an important part of my code arsenal now and is used on almost a daily basis.
Conclusion
I hope these console.log tips help you in your next project. They are great to know and can help you speed up your JavaScript development time as well as reduce errors or at least give you a way to better troubleshoot those errors. If you want to watch my videos when they premier, don't forget to subscribe to Dev Drawer on YouTube.