LWC & JavaScript debugging
If you're a Salesforce dev, here is something that may be really helpful when developing, testing or debugging your LWCs. On the other hand, if you're a JavaScript/Frontend developer, you will most likely consider this basic knowledge. I fall very easily into the first category, learning this is a real gamechanger for me, and I think it may be worthwhile to others as well.
Console.log() statements everywhere
When developing LWCs, we use console.log() VERY often to better observe what happens in our JavaScript code, and know what values variables have at a given time. It's a habit we got from working with Apex, where we always use System.debug() statements to print out values during runtime. Looking at any DEV sandbox, you will find console.log() lines in many LWCs. In many cases, also in higher orgs, as developers would sometimes leave the statements in place with the expectation that these statements will help debugging Production code. This is of course far from ideal, as we want to keep Production code clean.
A LWC JavaScript function may look something like this:
The console.log() statements will print out the desired value in the DevTools Console. Everyone is familiar with using the Console to see what happens in JavaScript code. But not everyone is aware of the other capabilities of a browser's DevTools.
Chrome DevTools Sources & Breakpoints: A better approach
Turns out, we don't need to always use console.log(), and in most cases, we don't even have to adjust our JavaScript code to be able to get the information that we need!
Modern browsers offer tools that allow us to step through JavaScript code, establish breakpoints, and watch variables and their values as they evolve during runtime.
Let's take a look at Chrome DevTools. This built-in browser tool can be brought up by simply pressing F12, or by clicking through the browser's menu.
Recommended by LinkedIn
The following example covers the same piece of JavaScript code, as the previous example:
Here are the key parts of DevTools that we need to access to see variable values during JavaScript execution:
And that's it - there's no more need to adjust your JavaScript code just to print out variable values. Instead you can do a few clicks and just sit back and watch what happens with your code.
There are a few things to keep in mind when looking at LWCs in DevTools:
In closing, Chrome DevTools offers many excellent ways to help us with development of front-end components, and this article is only scratching the surface. DevTools allows us watch how the browser communicates with the server (Network tab) and how resource-intensive and efficient our implementation is (Performance tab). It's always worthwhile to play around with useful tools and see what other help they can offer.
TIL!