JavaScript: The For Loop
The while loop is ideal for situations where the number of iterations is unknown in advance, for example, when searching for a prime number. When the number of iterations is known, it's preferable to use the for loop.
Let's look at the implementation of reversing a string using a for loop:
const reverseString = (str) => {
let result = "";
for (let i = 0; i < str.length; i += 1) {
result = `${str[i]}${result}`;
}
return result;
};It can be read as follows: the loop with index i repeats while i < str.length and increases i by 1 after each step.
Let's go through how the loop works step by step for the call reverseString('go!'):
before the loop: result = ''
i=0: result = `${str[0]}${result}` = 'g' + '' = 'g'
i=1: result = `${str[1]}${result}` = 'o' + 'g' = 'og'
i=2: result = `${str[2]}${result}` = '!' + 'og' = '!og'Each new character is prepended to the left of the accumulated result, so the string is built in reverse order.
In the definition of the for loop, there are three expressions inside the parentheses, separated by semicolons:
- The initial value of the counter. This code runs exactly once before the first iteration.
- The predicate — the condition for repeating the loops. It runs on every iteration. Just like in
while. - The description of how the counter changes. This code runs at the end of each iteration.
In all other respects, the principle of operation is exactly the same as the while loop.
Another example: counting characters
Let's count how many times a character occurs in a string, case-insensitively:
const charsCount = (text, char) => {
let result = 0;
for (let i = 0; i < text.length; i += 1) {
// convert to lowercase so as not to depend on the case
if (text[i].toLowerCase() === char.toLowerCase()) {
result += 1;
}
}
return result;
};
charsCount("hexlet!", "e"); // 2
charsCount("hExlet!", "E"); // 2
charsCount("hexlet!", "a"); // 0Here for controls the iteration over characters, while the condition inside decides whether to increment the counter.
In the for definition, you don't have to specify all three expressions. If you don't specify the loop repetition condition, the loop will run infinitely:
let i = 1;
// You don't even have to specify all three expressions
for (;;) {
console.log(i);
i += 1;
}Instructions
FizzBuzz is one of the most famous interview tasks for beginner programmers. It's given to test the ability to work with loops and conditions. Implement a function fizzBuzz(n) that returns a string with the numbers from 1 to n.
In this case:
- if a number is divisible by 3, the word
"Fizz"is substituted instead; - if it's divisible by 5 — the word
"Buzz"; - if it's divisible by both 3 and 5 — the word
"FizzBuzz".
All elements are joined with a space.
Example of calling the function:
fizzBuzz(15);
// => '1 2 Fizz 4 Buzz Fizz 7 8 Fizz Buzz 11 Fizz 13 14 FizzBuzz'Algorithm
- Declare the neutral element of aggregation (an empty string).
- Iterate through the numbers from 1 to
nwith aforloop. - Check the number against the divisibility conditions.
- Add the result of each iteration to the resulting string, separated by a space.
Tips
If you've reached a deadlock it's time to ask your question in the «Discussions». How ask a question correctly:
- Be sure to attach the test output, without it it's almost impossible to figure out what went wrong, even if you show your code. It's complicated for developers to execute code in their heads, but having a mistake before their eyes most probably will be helpful.
JavaScript: The For Loop
The while loop is ideal for situations where the number of iterations is unknown in advance, for example, when searching for a prime number. When the number of iterations is known, it's preferable to use the for loop.
Let's look at the implementation of reversing a string using a for loop:
const reverseString = (str) => {
let result = "";
for (let i = 0; i < str.length; i += 1) {
result = `${str[i]}${result}`;
}
return result;
};It can be read as follows: the loop with index i repeats while i < str.length and increases i by 1 after each step.
Let's go through how the loop works step by step for the call reverseString('go!'):
before the loop: result = ''
i=0: result = `${str[0]}${result}` = 'g' + '' = 'g'
i=1: result = `${str[1]}${result}` = 'o' + 'g' = 'og'
i=2: result = `${str[2]}${result}` = '!' + 'og' = '!og'Each new character is prepended to the left of the accumulated result, so the string is built in reverse order.
In the definition of the for loop, there are three expressions inside the parentheses, separated by semicolons:
- The initial value of the counter. This code runs exactly once before the first iteration.
- The predicate — the condition for repeating the loops. It runs on every iteration. Just like in
while. - The description of how the counter changes. This code runs at the end of each iteration.
In all other respects, the principle of operation is exactly the same as the while loop.
Another example: counting characters
Let's count how many times a character occurs in a string, case-insensitively:
const charsCount = (text, char) => {
let result = 0;
for (let i = 0; i < text.length; i += 1) {
// convert to lowercase so as not to depend on the case
if (text[i].toLowerCase() === char.toLowerCase()) {
result += 1;
}
}
return result;
};
charsCount("hexlet!", "e"); // 2
charsCount("hExlet!", "E"); // 2
charsCount("hexlet!", "a"); // 0Here for controls the iteration over characters, while the condition inside decides whether to increment the counter.
In the for definition, you don't have to specify all three expressions. If you don't specify the loop repetition condition, the loop will run infinitely:
let i = 1;
// You don't even have to specify all three expressions
for (;;) {
console.log(i);
i += 1;
}Instructions
FizzBuzz is one of the most famous interview tasks for beginner programmers. It's given to test the ability to work with loops and conditions. Implement a function fizzBuzz(n) that returns a string with the numbers from 1 to n.
In this case:
- if a number is divisible by 3, the word
"Fizz"is substituted instead; - if it's divisible by 5 — the word
"Buzz"; - if it's divisible by both 3 and 5 — the word
"FizzBuzz".
All elements are joined with a space.
Example of calling the function:
fizzBuzz(15);
// => '1 2 Fizz 4 Buzz Fizz 7 8 Fizz Buzz 11 Fizz 13 14 FizzBuzz'Algorithm
- Declare the neutral element of aggregation (an empty string).
- Iterate through the numbers from 1 to
nwith aforloop. - Check the number against the divisibility conditions.
- Add the result of each iteration to the resulting string, separated by a space.
Tips
If you've reached a deadlock it's time to ask your question in the «Discussions». How ask a question correctly:
- Be sure to attach the test output, without it it's almost impossible to figure out what went wrong, even if you show your code. It's complicated for developers to execute code in their heads, but having a mistake before their eyes most probably will be helpful.
Your exercise will be checked with these tests:
import { expect, test } from "vitest";
import f from "./index.js";
test("for", () => {
expect(f(3)).toEqual("1 2 Fizz");
expect(f(5)).toEqual("1 2 Fizz 4 Buzz");
expect(f(15)).toEqual("1 2 Fizz 4 Buzz Fizz 7 8 Fizz Buzz 11 Fizz 13 14 FizzBuzz");
});Teacher's solution will be available in:
20:00
