Home > Article > Web Front-end > The difference between continue in while and for javascript
JavaScript is a very popular programming language with a variety of syntax structures and control flows. Among them, while and for loops are very common in JavaScript programming. In both loops, there is a keyword "continue", which is used to skip an iteration in the current loop. However, there are some differences between them.
In the while loop, the function of the continue statement is to skip one iteration of the current loop. For example, you can use the continue statement to transfer control to the next loop iteration when a condition is not met. The following is an example of a while loop:
let i = 0; while(i < 10) { i++; if(i % 2 === 0) { continue; } console.log(i); }
In this example, when i is an even number, we use the continue statement to skip the current iteration and directly enter the next loop. Therefore, the output of this program will be 1, 3, 5, 7 and 9.
However, in a for loop, the use of continue is slightly different. The for loop has three expressions: initialization, condition and iterator. Initialization consists of a series of statements that are executed before the loop begins. The condition determines whether the loop should execute, and the iterator is executed at the end of each loop. The following is an example of a for loop:
for(let i = 0; i < 10; i++) { if(i % 2 === 0) { continue; } console.log(i); }
In this example, we use continue to skip the even numbers in the loop. When i is an even number, the continue statement will be executed and control will jump to the next iteration. Therefore, the output of this program will be 1, 3, 5, 7 and 9.
In general, in JavaScript, the continue keyword is used roughly the same in while and for loops, but it is more common in for loops than in while loops. In a for loop, the continue statement is often used to skip certain iterations in order to traverse the loop faster. But in the while loop, the use of continue statement is relatively rare.
In addition to the continue statement, JavaScript also has some other keywords and control flows, such as break, return, if-else statements, etc. Programmers should master the use of these control flows to improve code efficiency and readability.
The above is the detailed content of The difference between continue in while and for javascript. For more information, please follow other related articles on the PHP Chinese website!