According to the course,loops refer to DRY (Don’t Repeat Yourself). In the other word, we want to keep our code as DRY as possible. Loops offer a easy way to run the code repeatedly and save us a lot time.
While Loops
While loops is one kind of loops.It allows to repeat code While a condition is true.
while(someCondition) {
//run some code
}
While loops is very similar to an if statement, except it repeats a given code block instead of just running it once.
For example:
var num = 1;
while(num <= 10) {
console.log(num);
num += 2;
}
The example assumes a number is equal to 1 and gives a condition we run the (num +2) and count how many result are less and equal than 10.
When I run the loop in the console, the result:
The (num + 2) result less than 10 are 1, 3, 5, 7, 9. And it ends by 11 since 11 is greater than 10.
Infinite loops occur when the terminating condition in a loop is never true.
For example: var count = 0
while(count < 10) {console.log(count);}
This example prints “0” over and over because count is never incremented.
网友评论