Loops: while, do while and for
While and for are usually used for taking the same actions for different values, items.
Lets review "for" first
So the following code loops through new users and send them an email (we assume email function exists, that is just an example)
var newUsers = [{ID:1, "Alex Souzax"}, {ID:2, "Mathew Vlad"}, {ID:3, "Roberto Baggion"}];
for(var i=0;i<newUsers.length;i++){
SendWelcomeEmail(newUsers[i]); // Lets assume we have send email function exists
}
Lets do the same code with while
We have set the variable i to 0 first. Put the condition on while to execute the inner code until condition becomes false. In the inner code there is "i++" which increases i variable and when it hits the total user count it leaves the while loop. This is exactly the same thing as for loop we have above.
var newUsers = [{ID:1, "Alex Souzax"}, {ID:2, "Mathew Vlad"}, {ID:3, "Roberto Baggion"}];
var i = 0;
while(i<newUsers.length){
SendWelcomeEmail(newUsers[i]); // Lets assume we have send email function exists
i++;
}
Do while loop
Difference between do while and while loop is as the following;
do while loop executes the inner code without checking the condition first than on second round it starts checking the condition
On the following code the out put will be "current i value is 0" as it is not checking the condition first.
var i = 0;
do{
console.log("current i value is " + i);
i++;
}
while(i<0)
On the following code there will be no output it is checking the condition on the first round.
var i = 0;
while(i<0){
console.log("current i value is " + i);
i++;
}
- Comment Your JavaScript Code
- Declare Variables
- Data Types
- Type Conversions
- + Plus Operator
- - Minus Operator
- * Multiply Operator
- * Multiply Operator (1)
- % Modulus (Division Remainder) Operator
- ** Exponentiation Operator
- Bitwise operators
- Comparisons
- Logical Operators
- Interaction: alert, prompt, confirm, console.log
- The "switch" statement
- Loops: while, do while and for