Decision Making in JavaScript.

Decision Making in JavaScript.

(30 Days of JavaScript)

ยท

2 min read

A conditional/decision-making construct evaluates a condition before the instruction(s) are executed.

Decision Making statements are if, else, elseif and switch these statements are used in making decisions.

Screenshot_20210529-140755[1].png

if..else statements

if..else statements is used where you want to execute a set of code when a condition is true and another if the condition is not true.

Syntax:

if (condition)
{
  code to be executed if condition is true
}
else
{
  code to be executed if condition is false
}

Example of if..else

var a=10;
if (a==10)
{
  echo "Yes the value is 10"; 
}
else
{
  echo "No the value is not 10"; 
}

elseif statements

elseif statements is used where you want to execute a some code if one of several conditions are true use the elseif statement.

Syntax:

if (condition)
{
  code to be executed if condition is true
}
elseif (condition)
{
  code to be executed if condition is true;
}
else
{
  code to be executed if condition is false
}

Example of elseif

var a=10;
if (a==20)
{
  echo "Yes the value is 20"; 
}
elseif(a==10)
{
  echo "Yes the value is 10"; 
}
else
{
  echo "No you are wrong"; 
}

switch statements

switch statements is used where you want to execute one block of code out of many.

Syntax:

switch (value)
{
case value1:
  code to be executed if value = value1;
  break;  

case value2:
  code to be executed if value = value2;
  break;

default:
  code to be executed
  if value is different 
  from both value1 and value2;
}

Example of switch:

var a=10;
switch ( a )
{
case 10:
  code to be executed if var a=10;
  break;  

case 20:
  code to be executed if var a=20;
  break;

default:
  code to be executed
  if value is different 
  from both value1 and value2;

}

We'll discuss extensively in the other topics.

Did you find this article valuable?

Support Bode's blog by becoming a sponsor. Any amount is appreciated!