Javascript Decision Making with If-Else – POFTUT

Javascript Decision Making with If-Else


Programs are mainly written on decisions. Decisions makes an application more flexible and rich. Javascript supports decisions too. A decision example might be like this: If person age above 17 set him adult.

Single If

We can define more complex decisions but for now we will look into simple decision.

var age=19;

if(age>17){
 console.log("You are adult");
}
  • if is the starting expression of the decision tree.
  • (age>17) is the condition we want to check. If this condition is true. Between { } code will run.
  • The output will be “You are adult”

Multiple Conditions – if else

Previous example was simple just looks for above age. What is look below age too. For example if age is between 7 and 18 we want to call him student.

var age=10;

if(age>17){
 console.log("You are adult");
}else if(age>6){
 console.log("You are student");
}
  • else if adds new situation for the decision tree.
  • (age>6) looks for above 6.

Multiple condition tree works from up to down. If one of condition is satisfied decision tree ends.

Default Condition – else

We can define a default condition at the end of the decision tree for no match. Say age is below 7 we assume he is an infant without checking the age.

var age=5;

if(age>17){
 console.log("You are adult");
}else if(age>6){
 console.log("You are student");
}else{
 console.log("You are infant");
}
  • else is used to if nothing matches. else do not needs a condition because it is the latest and default.

LEARN MORE  Ternary Operator In Java Tutorial with Examples

Leave a Comment