Зарегистрируйтесь для доступа к 15+ бесплатным курсам по программированию с тренажером

Mutators and for loop —Intro to Programming

Video may be blocked due to browser extensions. In the article you will find a solution to this problem.

Lesson notes

Arithmetic shortcuts:

b *= a;    // same as b = b * a
b += a;    // same as b = b + a
b -= a;    // same as b = b - a
b %= a;    // same as b = b % a

Increment and decrement operators:

// Postfix
let a = 3;
let b;
b = a++;    // b = 3, a = 4

// Prefix
let a = 3;
let b;
b = ++a;    // b = 4, a = 4

Example of a for loop:

const factorial = (n) => {
let result  = 1;

// initialization↓    condition↓     update↓
for (let counter = 1; counter <= n; counter++) {
result *= counter;
}

return result;
}

Lesson transcript

Well, this lesson is going to be quick and easy, so, buckle up.

Recall the factorial function with a while loop:

const factorial = (n) => {
let counter = 1;
let result  = 1;

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

return result;
}

When we deal with variables, we often do this — change their values by adding something to them or multiplying them by something. Or simply adding or substracting one.

Like many other programming languages, JavaScript has shortcuts for this.

Instead of result = result * counter you can say result *= counter. The result will be the same, this is just a shorter way to write it. And you can do the same with plus, minus and divide:

result *= counter;    // same as result = result * counter
result += counter;    // same as result = result + counter
result -= counter;    // same as result = result - counter
result %= counter;    // same as result = result % counter

Adding one to a variable is also very common, so instead of counter = counter + 1 you can say counter++. The same goes for minus — counter = counter - 1 is the same as counter--. These are the increment and decrement operators.

There are two ways to use them, and it's easy to understand with an example:

// Postfix
let a = 3;
let b;
b = a++;    // b = 3, a = 4

// Prefix
let a = 3;
let b;
b = ++a;    // b = 4, a = 4

If you put ++ after the variable name — this is a postfix notation — then the actual adding happens after the value is returned. This is why b is 3 here: it gets the value before a is changed.

If you put ++ before the variable name — this is a prefix notation — then the actual adding happens before the value is returned. This is why b is 4 here: it gets the value after a is changed.

But in the end in both cases a becomes 4.

This is the updated factorial function:

const factorial = (n) => {
let counter = 1;
let result  = 1;

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

return result;
}

Here it doesn't matter if we use prefix or postfix when incrementing counter, because the value is not being stored anywhere else.

This code is a bit simpler and shorter. Having a loop — this repeating code — with a counter controlling the repetitions is a common thing in programming. That's why in addition to while loops there are also for loops. They kind of have built in counters.

Here is the same factorial function, but with a for loop instead of a while loop:

const factorial = (n) => {
let result  = 1;

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

return result;
}

There are three expressions:

1. Initialize the counter.
2. Loop condition. Just like in a while loop, this loop will repeat while this condition is true.
3. Counter update. How to change the counter every step.

And then goes the body, the code that's going to be repeated. We don't need to change the counter in the body, because it's going to be changed thanks to that expression above.

It's time to use all this fancy knowledge and write some code! Continue to the quiz and the exercise already! Are there any more questions? Ask them in the Discussion section.

The Hexlet support team or other students will answer you.

Ошибки, сложный материал, вопросы >
Нашли опечатку или неточность?

Выделите текст, нажмите ctrl + enter и отправьте его нам. В течение нескольких дней мы исправим ошибку или улучшим формулировку.

Что-то не получается или материал кажется сложным?

Загляните в раздел «Обсуждение»:

• задайте вопрос. Вы быстрее справитесь с трудностями и прокачаете навык постановки правильных вопросов, что пригодится и в учёбе, и в работе программистом;
• расскажите о своих впечатлениях. Если курс слишком сложный, подробный отзыв поможет нам сделать его лучше;
• изучите вопросы других учеников и ответы на них. Это база знаний, которой можно и нужно пользоваться.
Об обучении на Хекслете

• 130 courses, 2000+ hours of theory
• 900 practical tasks in a browser
• 360 000 students
By sending the form, you agree to "Personal Policy" and "Service Conditions".    Используйте Хекслет по максимуму!

• Задавайте вопросы по уроку
• Проверяйте знания в квизах
• Проходите практику прямо в браузере
• Отслеживайте свой прогресс