All posts | Code

The Simplest Debugging Technique in JavaScript

It's very easy to make mistakes when you have to handle variables, change them, keep track of them, etc., especially in a loop. A great way to understand what's going on is to use the simplest debugging tool of all — console.log. This function prints onto the screen whatever you pass to it.

I have a function that iteratively calculates the factorial. The idea is simple: multiply numbers from 1 up to n. I wrote the code, but it gives me the incorrect result. I'm trying to understand what's happening inside the main while loop:

while (counter <= n) {
  result = result * result;
  counter = counter + 1;
}

I'm going to add console.log here to see how result is being changed over time:

while (counter <= n) {
  result = result * result;
  counter = counter + 1;
  console.log(result)
}

Now, each time this block of code repeats, the result variable will be printed. Let's see:

1
1
1

(I'm running the function with n equals 3)

The result in each step is 1. This is not right, the result should increase each step... Okay, so, the problem is probably in the line where result is changing. Right! I have result = result * result, but I need to multiply result by counter, not by result.

Let's fix it:

while (counter <= n) {
  result = result * counter;
  counter = counter + 1;
  console.log(result)
}

1
2
6

Now it works! I see the steps now, and the last step produces the correct answer: 3! is 6.

Don't hesitate to put console.log wherever. It's your best friend :-)

User avatar R. D.
R. D. 19 January 2017
Suggested learning programs

From a novice to a developer. Get a job or your money back!

Frontend Developer icon
Profession
beginner
Development of front-end components for web applications
start anytime 10 months
Layout Designer icon
Profession
New Under development beginner
Layout with the latest CSS standards
start anytime 5 months