Debugging in LWC

Let us look at some interesting ways to debug LWC.

Lightning Web Components are completely built on JavaScript and it is extremely important that we get better at debugging the JavaScript code in Lightning Web Components.

Using debugger keyword

Where ever we want to add the breakpoint we can sneak in a keyword called `debugger` in the controller file of the LWC.

In runtime (when dev tools panel is opened up) the moment code hits the debugging point execution stops and it allows the developers to check runtime values.

Pro's

The main advantage of using the debugger keyword is when we are not aware which piece of code gets executed and for some reason, if you are not able to locate the file under source tab in dev tools, debugger keyword is going to make sure the file is opened up the moment execution encounter the keyword `debugger`

Con's

In runtime when you want to add more debuggers to the code we cannot do it. We need to go back to the code, make the changes and then rerun the component to see if the new debugging points are hit.

Using Chrome Debugger

One of the amazing features in Chrome's suite of dev tools is javascript debugger.

Trust me on this, it's is a game-changer.

It is as simple as opening the chrome browser, right-click, select inspect, select source tab, from the left side panel select the JavaScript file, apply breakpoints.

Steps to follow to apply break points

In runtime where ever and whenever we want to add a breakpoint we can click slightly to the left of the line number once the file is opened up from the source tab.

Applying break point and adding a few more in runtime

When we run the component once the execution hits the breakpoint, the execution stops and we can look at the runtime values.

To out comfort, chrome team has also provided us a few controls that you will find to the top right of the dev tools.

  1. In case you are not interested in adding a hell lot of breakpoints you can use the step over icon that is right beside the play icon to execute the code in the current line (or underlying function in case it's a function) and execution jumps on to the next statement.
  2. If you want the execution to get into a function and stop at the first line you need to use the step into current function call icon.
  3. If you want to finish off executing the code in the underlying function, come out of the function and stop the execution at the next line you need to rely on step out of current function icon

Pro's

Lot more handy! It cannot get easier than this.

We don't have to go back to the code, make changes and refresh the component to debug at the new breakpoints.

We can debug the code line by line and jump over functions that you wish to ignore.

Con's

I can't think of any!