JavaScript: Returning from loops
Working with loops usually comes down to two scenarios:
- Aggregation. Accumulating a result during iterations and working with it after the loop. Reversing a string is exactly this kind of case.
- Running the loop until the required result is reached and then exiting. For example, the task of finding prime numbers. Recall that a prime number is a number that is divisible without a remainder only by itself and by one.
Let's look at a simple algorithm for checking whether a number is prime. We'll divide the target number x by all numbers in the range from two to x - 1 and look at the remainder of the division. If no divisor that divides x without a remainder is found in this range, then we have a prime number.
Checking whether 5 is prime: a step-by-step walkthrough
- Take the number
x = 5. We look for possible divisors in the range from 2 tox - 1, that is, from 2 to 4. - Divide 5 by 2. The remainder is 1 — no divisor found, continue.
- Divide 5 by 3. The remainder is 2 — no divisor found, continue.
- Divide 5 by 4. The remainder is 1 — no divisor found, finish the search.
Result: in the range 2…4 there was no number by which 5 is divisible without a remainder. Therefore, 5 is a prime number.
If you think about it, you can notice that it's enough to check numbers not up to x - 1, but up to half of the number. For example, 11 is not divisible by 2, 3, 4, 5. And beyond that it is guaranteed not to be divisible by numbers larger than its half. So we can make a small optimization and check division only up to x / 2.
const isPrime = (number) => {
if (number < 2) {
return false;
}
let divider = 2;
while (divider <= number / 2) {
if (number % divider === 0) {
return false;
}
divider += 1;
}
return true;
}
isPrime(1); // false
isPrime(2); // true
isPrime(3); // true
isPrime(4); // falsewhile (...) {
if (condition) {
return value; ← exit from the function (and from the loop)
}
...
}
─────────────────────────
Without return the loop continues to the endThe algorithm is built like this: if during the sequential division by numbers up to x / 2 at least one is found that divides without a remainder, then the passed argument is not a prime number, and further calculations make no sense. At this point there is a false return.
And only if the loop has run completely and no number that divides without a remainder was found, can we conclude that the number is prime.
To be completely honest, checking numbers up to the square root of number is enough to solve the task. But here it's important for us to focus on understanding how to work with conditions and returning inside a loop.
Instructions
Implement the function hasAtSymbol(), which checks whether an email contains the @ symbol.
The function should return true as soon as it finds @. If the loop reaches the end of the string and the symbol is not found, return false.
hasAtSymbol('support@example.com'); // => true
hasAtSymbol('wrong-email'); // => false
hasAtSymbol('@admin'); // => trueUse a loop with an early return.
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.
Tests are designed so that they test the solution in different ways and against different data. Often the solution works with one kind of input data but doesn't work with others. Check the «Tests» tab to figure this out, you can find hints at the error output.
It's fine. 🙆 One task in programming can be solved in many different ways. If your code passed all tests, it complies with the task conditions.
In some rare cases, the solution may be adjusted to the tests, but this can be seen immediately.
It's hard to make educational materials that will suit everyone. We do our best but there is always something to improve. If you see a material that is not clear to you, describe the problem in “Discussions”. It will be great if you'll write unclear points in the question form. Usually, we need a few days for corrections.
By the way, you can participate in courses improvement. There is a link below to the lessons course code which you can edit right in your browser.
Создавать обучающие материалы, понятные для всех без исключения, довольно сложно. Мы очень стараемся, но всегда есть что улучшать. Если вы встретили материал, который вам непонятен, опишите проблему в обратной связи нашего сообщества
Your exercise will be checked with these tests:
import { expect, test } from 'vitest';
import f from './index.js';
test('test', () => {
expect(f('support@example.com')).toBe(true);
expect(f('wrong-email')).toBe(false);
expect(f('@admin')).toBe(true);
expect(f('a@b')).toBe(true);
});Teacher's solution will be available in:
20:00
