Javascript If-Else Statement

Javascript If-Else

Conditional statements are the very basic building blocks of any program. If the condition is true then follow the defined statements else follow some other set of defined statements. Javascript like all the programming languages has its own syntax for it.

if (condition){
   statement1;		//These statements will be executed when condition is true
   statement2;
}
else{
   statement1;		//These statements will be executed when condition is false
   statement2;
}

What if we want to check multiple conditions or want to write multiple statements according to different conditions.

if (condition1)
   statement1;
else if (condition2)
   statement2;
else if (condition3)
   statement3;
else
   statement4;

If we are writing a single statement then no need to enclose it within paranthesis.

if (condition1 && condition2)
   statement1;
else if (condition3 && condition4)
   statement2;
else if (condition5)
   statement3;
else
   statement4;

Logical operators will be used like this.

The examples seems quite hard to understand, but when linked with a real life example they are simple to unserstand.

var age = 19;
if (age<18)
   console.log("Not eligible to vote");
else
   console.log("Eligible to vote");

console.log() is a function to print in browsers’ console. This code has a bug. Can you find it and solve it –>

var age = 19;
var gender = 'M';
if ((age<18) && (gender==='M'))
   console.log("You are less than 18 and a male");
else if ((age>=18) && (gender==='M'))
   console.log("You are 18 or more and a male");
else ((age<18) && (gender!=='M'))
   console.log("You are less than 18 and a female");
else
   console.log("You  are 18 or more and a  female");

Nested conditional statements

var age = 19;
var gender = 'M';
if (age<18){
	if(gender==='M'){
		console.log("You are less than 18 and a male");
	}
	else{
		console.log("You are less than 18 and a female");
	}
}
else{
	if(gender==='M'){
		console.log("You are 18 or more and a male");
	}
	else{
		console.log("You are 18 or more and a female");
	}	
}

Assignment

  • Write a condition to check if triangle is Equilateral, isoceles or scalene given all the 3 sides.
  • Write a condition to check the average marks of 5 subjects and grade accordingly.
    1. Grade A if average marks >= 85
    2. Grade B if average marks >=65 and <85
    3. Grade C if average marks >=45 and <65
    4. Grade D otherwise

Solutions

var sideA;
var sideB;
var sideC;
if(sideA===sideB && sideB===sideC)
	console.log("Equilateral");
else if(sideA===sideB || sideB===sideC || sideC===sideA)
	console.log("Isoceles");
else
	console.log("Scalene");
Translate ยป