Decisions

Sometimes when we are programming we will have to make decision to execute one blockof code based on some condition. to make this happen we can use one of these decision statements.

  • If/else

  • Switch

Expression

  • Ternary ? Operator

If/else

  • if statements need an expression.

  • if the expression evalutes to true the block containing alert function will be excuted and will say the output.

ex-

let age = 18
if(age>8){
alert("you are a child")
}

Output is execute because expression is true.

let age = 18
if(age<8){
alert("you are a child")
}

Output is not execute because expression is false.

Switch

  • A switch statement needs a exression and tells the eqality with different cases.

  • When the match is found the associated block will be executed until the nearest break statements.

  • If the case not match the default block will be executed.

ex-

let num =2
Switch(num){
case 1:
alert("ONE")
break;

case 2:
alert("TWO")
break;

case 3:
alert("THREE")
break;

 default:
alert("match not found")

let See Output
-In output we see TWO because value of num is 2.
-it will match with case-1 that is false.
-match with case-2 then it is true and match block will be executed until the  
nearest break statement.

Note

  • if we remove the break statements then it will keep executing until the last line of the code.

Ternary Operator ? (conditional operator)

  • It si the shorter version of if/else

  • it is called ternary operator beacuse it takes 3 Operands.

  1. Condition
  2. Exepression 1
  3. Exepression 2(when Condition is true expression 1 gets written otherwise expression 2)

ex- Converting if/else into ternary operator

let age = 16
age<11?
alert("you are a child!")
: 
alert("you are a teen!")

Q/A

Ques- what is the main difference between if/else and ternary operator?
Ans-  if- is a statement   
      ternary operator- is a expression