[Learning] #16 JS: loop — Part 1

while statement

If the statement is true, the code inside of {} would be executed.
When the first execution is done, the system will return to the while to repeat the execution.
The loop will stop until the result becomes false.

var n=0;
while(n<=50) {
n++;
}
alert(n);

var sum=0;
var i=1;
while(i<=100){
sum=sum+i; → it can be written as sum+=i as well.
i++;
}
alert(sum);

for statement

  • The concept of while and for is similar, but for combines 3 important blocks together, which makes the code simpler.
  • Each of the statement means: for(initialization command;statement for decide whether the next loop continues;execute after every loop){
    }
var sum=0;
for(var i=1;i<=100;i++){
sum=sum+i;
}
alert(sum);

break & continue

  • break; → “jumps out” of a loop (強制跳出迴圈)
  • continue; → “jumps over” one iteration in the loop (強制進行下一次的迴圈)
    by W3C Schools

Example 1. while statement x break

var n=0
while(n<=100){
if(n==50){
break;
}
n++;
}
alert(n);

=>n is 50.

Example 2. for statement x continue

var x=0;
for(var n=0;n<=100;n++){
if(n%4==0){ → n can be divided exactly by 4.
continue;
}
x++;
}
alert(x);

=>x is 75.

--

--

--

PM, Relationship, Travel, or anything quirky but interesting.|Subscribe & buy Vida a drink @LikerLand, the bottom of each article. 在文章底下LikerLand訂閱、請Vida喝一杯飲料 ❤

Love podcasts or audiobooks? Learn on the go with our new app.

Redux Is Dead, Long Live Redux

How to Block Zero Day Threats in Node.JS

Dissecting GraphQL Queries

How ad blockers are blocking my site

JavaScript overrides made interesting -Part 1

How to Create Multi-Module Node.js Applications

How to Run React Projects

How I built an autoupdate mechanism in electron by using gitlab

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Vida Lin

Vida Lin

PM, Relationship, Travel, or anything quirky but interesting.|Subscribe & buy Vida a drink @LikerLand, the bottom of each article. 在文章底下LikerLand訂閱、請Vida喝一杯飲料 ❤

More from Medium

How to Fix JavaScript Runtime issues — Lazy Loading

JavaScript 30 — Array Cardio 1

How To Start npm Project?

JS conceptual 2