Hi I would appreciate if I could have an assessment of my work on Test your skills: Loops.
I struggled quite a lot, so there are many questions… Sorry in advance, but I’d really appreciate if you could help me!
My work Loop 1
Loop 2
I could make it work with for loop and if conditions (solution 1),
but I wanted to try if I can do this with switch statements (solution 2 & 3).
Solution 2 worked, but feels a little weird that it worked.
Is it allowed to write the second case like this, not just a value, but with comparison operator?
I originally wrote default as below, but with default, it didn’t work. Why?
Solution 3 did not work. I think the second case may be the problem but don’t know why…
Loop 3
Even though I could make it work with for loop (solution 1),
I wanted to use while loop because I haven’t used it for other tests, but I couldn’t make it work (solution 2).
CodePen showed an error message “Infinite loop found around line 0.”
I thought I didn’t make an infinite loop though… How can I make this work?
Solution 1 is ok, but you could remove the else if part and just write the “Not found” text after the if. This works because you use break to jump out of the for loop as soon as a name was found.
Solution 2 with default and solution 3 don’t work, because break just leaves the switch, but the loop still runs through the whole array. This causes the textContent to be overwritten every round. It only works when you search for “Jada”, because it’s the last entry.
Technically using switch can work this way, but i think we both agree that it’s not the ideal tool for the job. Just use it if you have multiple values. For a simple yes/no question you should prefer the if statement.
Task 3
Solution 1:
Using if(!isPrime(i)) also works for function calls. The function return a boolean (true or false) so we can handle it the same like a variable that contains true/false.
The continue is not needed since the other lines are behind else statements.
Solution 2:
The continue cause the exit the current round of the loop, which also skips the i--. So i is always 500 infinite loop.
After the else if the condition should just be i === 2.
A working solution (with a do...while loop) could look like this:
do {
if (isPrime(i)) {
para.textContent += `${i} `;
}
i--;
} while (i > 1);
I’m a little bit confused In solution1, break makes it jump our of the loop, but in solution2, break only exits switch but stays in the loop…?
Is it perhaps the difference between when you use break in if and when you use break with switch?
break; has only an effect on the current loop or switch. if statements are ignored. So they only break out from the first loop/switch that’s around them.
There is a concept called label. With that you could give your outer loop a name and break out of it (even if the break is nested in multiple other loops/switches). Personally, I haven’t used labels, yet.