Matthew Orndoff

Matthew Orndoff

Front-End React Developer. I can do all things through Cold Brew 🙏

JavaScript Debugging

I used to fill my code up with console.log() calls to figure out what my JavaScript code was doing.

But I have found the light, there is a better way!

(Click here if you don’t care about backstories and want to get right to it)

The problem

Today I was working through a basic JavaScript data structures course.

I was stuck on a solution to this problem.

The challenge asked you to:

  1. Filter a through nested array using only for loops.

  2. Throw out any inner arrays which contained the argument passed into the elem parameter.

  3. Return a new filtered array.

Here was my solution:

(TL;DR It’s WRONG)

function filteredArray(arr, elem) {
let newArr = [];

for(let i = 0; i < arr.length; i++){
for(let i = 0; i < arr[i].length; i++){
if (arr[i] === elem) break;

if (i === (arr[i].length - 1)){
newArr.push(arr[i]);
}
}
}

return newArr;
}

The function wasn’t doing what I expected.

I stared at my screen for a few minutes trying to figure out what I was doing wrong in my head.

That’s when it hit me: "Wait, I’m smarter than this… open the debugger!"

Debugging in Devtools

I recently discovered a useful tip about debugging in Devtools.

When you define a function inside the Devtools console, you can pass that function into another function: debug()

Then when you run your function again, it will enter into the debugger!

Execution is paused on the first line, and you can begin to inspect what’s happening as the function runs.

The process

  1. I defined my function filteredArray by pasting it into the console.

  2. Ran debug(filteredArray)

  3. Then I ran filteredArray([[3, 2, 3], [1, 6, 3], [3, 13, 26], [19, 3, 9]], 3) which opened the function up in devtools! (See below).

After pressing F9 a few times, stepping through the execution process, I noticed that my logic was wack.

Paying attention to the “Scope” pane on the right-hand side (which tracks values in variables), I found out I wasn’t drilling down correctly into the arrays.

The Solution

I was able to revise my function to arrive at this solution! And while there are doubtlessly better ways to do it, this function had the bonus of … actually working.


function filteredArray(arr, elem) {
let newArr = [];

for(let j = 0; j < arr.length; j++){
for(let k = 0; k < arr[j].length; k++){
if (arr[j][k] === elem) break;

if (k === (arr[j].length - 1)){
newArr.push(arr[j]);
}

}
}
return newArr;
}

I probably could’ve stared at my screen longer to solve the issue.

Maybe pulled out a pen and pencil… slowly stepping through the process.

But debuggers exist for a reason.

And this is one of them. They help you save time.

Use your debugger!

Comments