Simple if branch
here a statement is executed based on condition
if (true) {
console.log('entered') // prints 'entered' as condition is true
}
if..else branch
here either statement is executed based on condition
if (0>1) {
console.log('greater than one')
} else {
console.log('less than one') // prints 'less than one' as condition is not satisfied
}
if..else if..else branch
here one of the statement block is executed based on condition. we can chain multiple condition by using 'else if'
var i = 0;
if (i > 1) {
console.log('greater than one')
} else if (i == 0) {
console.log('value is zero') // prints 'value is zero' as condition is not satisfied
} else {
console.log('less than one')
}
switch branch
this is similar to else..if chain. I the condition is based on single value then switch can be used.
In switch, The interpreter checks each case against the value of the expression until a match is found. If nothing matches, a default condition will be used. This match uses strict check i.e ===. break plays a very important role in switch.
var grade = 'A';
switch (grade) {
case 'A':
console.log('great job')
break
case 'B':
console.log('well done')
break
default:
console.log('Unknown grade')
} // prints 'great job'