// while vs do...while loops
/* while loops: check condition first. If true, execute code. */
let i = 0;
while (i < 5) {
console.log(i); // 0 1 2 3 4
i += 1;
}
/* do-while loops: execute code at least once even if condition is false.
Then check condition. If true, continue executing code. */
let j = 6;
do {
console.log(j); // 6
j += 1;
} while (j < 5);
var result = '';
var i = 0;
do {
i += 1;
result += i + ' ';
}
while (i > 0 && i < 5);
// Despite i == 0 this will still loop as it starts off without the test
console.log(result);
/*
`do while` is essentially like the basic `while` statement
except for one key difference, the body is always executed
at least once.
Syntax:
do {
body
} while (condition);
This is generally only useful if you need the body to run
at least once, before the condition is checked.
*/
let i = 10;
do {
console.log(i);
i--;
} while (i > 0);
/*
Outputs:
10
9
8
7
6
5
4
3
2
1
*/
let arr = ['jan', 'feb', 'mar', 'apr', 'may'], i = 0;
// do something at least 1 time even if the condition is false
do{
console.log(arr[i]);
i++;
}while(arr.includes('dec'));
// output: jan
let i =0
do{
console.log(i)
i++;
}
while(i>10);// even i =0 which is not greater then 10 it will console.log 0 for
//time as it execute code at least first time
var i = 1; // initialize
while (i < 100) { // enters the cycle if statement is true
i *= 2; // increment to avoid infinite loop
document.write(i + ", "); // output
}
//First, declare a variable for initial value
const doWhile = 10;
//Second, get do-while and write what to execute inside do bracket.
//Then, write ++/-- according to your condition.
//Lastly, inside while bracket write your condition to apply.
do{
console.log(doWhile)
doWhile--
}while(doWhile >= 0)