-
Notifications
You must be signed in to change notification settings - Fork 0
06 Control Structures
Usually the statements execute one after another
- However using control flow statements / control structures we can control which statements to execute
- how many times to execute etc.
If the condition is true then the if block gets executed.
let flag=true;
if(flag){
console.log('condition met')
}If we put flag = false then the if block will not be executed.
If the condition satisfies then it will execute the statement within the if block else the statement from else block.
let age=29;
if(age>30)
{
console.log('age is greater than 30');
}
else
{
console.log('age is less than 30');
}We can put condition inside another condition using nested if else.
let name='biswajit';
let salary= 300;
if(name == 'biswajit')
{
if(salary == 300)
{
console.log('Biswajit salary is 300');
}
else
{
console.log('Biswajit salary is not 300');
}
}
else
{
console.log('You are not Biswajit');
}This will execute statement(s) multiple times. Loops have three parts - initialize counter, condition check and counter increment. First it will initialize the counter like i=0 then it will check the condition i<5 then it goes to the loop body and executes the statement, then it increments the counter and checks the condition. the process continues until the condition fails.
for (let i=0; i<5; i++)
{
console.log("\n i = "+i);
}let j=0;
while(j<5)
{
console.log('\n j='+j);
j++;
}This is same as while loop however the only difference is first time, it enters to the loop without checking the condition and from second iteration onwards it checks the condition.
let k=5;
do
{
console.log('\n K='+k);
k++;
} while(k<5);When we have multiple possible conditions to check using the If-Else will be cumbersome. The effective approach would be to use switch case.
let day="monday";
switch(day)
{
case "monday": console.log('Today is Monday');
break;
case "tuesday": console.log('Today is Tuesday');
break;
default: console.log('Invalid input');
}let input=1;
switch(input)
{
case 1: console.log('Switch is on');
break;
case 0: console.log('Switch is off');
break;
}switch(new Date().getDay()){
case 4: console.log('Thursday');
break;
default: console.log("I don't know");
}The continue statement terminates the execution of the current iteration. It continues with the next iteration of the loop. In the example below it's going to print only 5 because everytime the if condition is satisfied it will break the current iteration and move to the next iteration of the loop.
let number = 0;
while(number < 5){
number++;
if(number < 5){
continue;
}
console.log(number)
}