Hexlet doesn not really work properly in your browser, because it is pretty old. Please, upgrade.

Hexlet's blog

Studying and living computer programming
3 days ago, Rakhim Davletkaliyev

DevelopmentThe Simplest Debugging Technique in JavaScript

It is very easy to make mistakes when you have to handle variables, change them, keep track, etc. Especially in a loop. A great way to understand what's going on is to use the simplest debugging technique — 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 :-)

Read more →
07 December 2016, Rakhim D.

HexletLearn The Basics of Programming With Us

We are launching our new study program in English. The first course — Intro to Programming — has started yesterday, new lessons come out every Tuesday and Friday. It's free!

  • Starting from lesson 2 each there are exercises and quizzes.
  • Lessons include additional materials: recommended reading and watching, illustrations, lecture notes, etc. Gotta dive in seriously!
  • Our team answers all the questions you might have in the Q&A section.
  • Few times a month we host a live Q&A session on YouTube.

Follow us to get updates on new lessons and important updates:

Any questions? Drop us a line at support@hexlet.io.

Read more →