This code is designed to display prime numbers, I can not understand how it works step by step:

nextPrime: for (var i = 2; i < 10; i++) { for (var j = 2; j < i; j++) { if (i % j == 0) continue nextPrime; } alert( i ); // простоС } 

Cycle is running for i, i.e.

  • there is a check j <i, in this case it is wrong 2 <2
  • the alert goes further and displays 2
  • i increases by 1
  • there is a check 2 <3, passes further
  • remains remains 1
  • alert (3) is running
  • variables increase by 1
  • 3 <4
  • alert (4)
  • still increasing 4 <5
  • alert (5)
    etc.

But it's not like that.
In theory, the step: i/j++ is performed after the body at each iteration, but before checking the condition, if you follow the syntax of the language, therefore, the check will fail and all numbers up to 9 will be displayed; but in fact it is not.
I am new to JS, but I would like to immediately understand what was happening ... Can you please explain why this is happening?
This question is intended to understand the sequence of actions in cycles.

  • one
    Possible duplicate question: Difference between FOR loops in JS - Visman
  • @Visman, here continue with the label, a little different all the same "for". - Rolandius
  • @Rolandius, so what, with the label, the meaning of that question is not far away. - Visman
  • one
    @Visman, not a duplicate! The team is different. continue LABEL; and continue; - these are different teams. - Qwertiy ♦
  • one
    @Visman, and let's still "the same programming language - all questions are duplicates";) - Qwertiy ♦

1 answer 1

In JS, there are no jumps in the label, but there are still and break statements that actually look like continue <ΠΌΠ΅Ρ‚ΠΊΠ°> and break <ΠΌΠ΅Ρ‚ΠΊΠ°> .

What is the essence. You can mark a for or while label, like this:

 label: for (;;) { // дСйствия } 

What happens when the interpreter finds continue <ΠΌΠ΅Ρ‚ΠΊΠ°> in a loop. If there is no label , it simply performs the next iteration. If it is, then performs the next iteration of the loop marked with this label. By the way, this is the only possible way in JS to affect from the inner loop to the outer loop. Actually, that was your question (by continue nextPrime; next iteration of the outer loop was performed).

For the sake of justice, you need to tell about break <ΠΌΠ΅Ρ‚ΠΊΠ°> . If the interpreter finds this statement without a label in the for and while loops, then it interrupts the execution of the loop, in the switch block it leaves the loop. The main difference between this operator and continue <ΠΌΠ΅Ρ‚ΠΊΠ°> is that it can be used outside the cycle blocks and the switch statement, then it is necessary to write a label and any block {} can be selected as a label, for example:

 label: { console.log('1'); break label; console.log('2'); } 

In this example, the interpreter reaches a break label; will find this tag and go to the end of this block ( 2 will not be displayed in the console).