If...Else Conditions
Introduction to Conditions
Conditioning is Very Important in Every Programming Language, it provides us a way to compare things and then perform the actions according to the condition given.
For Example :
Let's Suppose you have three options, one is to Pursue B.Tech, and the second is to Pursue B.Sc .and the third is to pursue BCA and you are a little confused about them. Then your mind will work like this :
If you Go Towards B.Tech then you have many options to become Like Software Engineer and Hardware Engineer etc.
or If you Go Towards B.Sc then you have some other option.
or else if you Go Towards BCA then you have other career options.
Javascript also works the same as Mind, it has a condition statement If...Else if...Else to compare the things and give output accordingly.
If...Else if....Else Declaration
In JavaScript we have the following conditional statements:
- Use if to specify a block of code to be executed, if a specified condition is true
- Use else to specify a block of code to be executed, if the same condition is false
- Use else if to specify a new condition to test, if the first condition is false
Syntax :
Example :
Here,
We are using If...Else Condition for Getting the Mobile Charging State.
if mobile's battery is 95 then it will print Mobile is Charged
or if mobile's Battery is less than 90 then it will print Mobile is Sufficiently Charged.
Let's Go Deep into Above Mobile Charging Example.
For More than Two Conditions, you have to use Else If.
If you want to make a program that tells you when your mobile needs charging when it is sufficiently charged so that you can continue your work and when it is fully charged.
Code :
Here,
We are using If...Else if...Else Condition for Getting the Mobile Charging State.
if mobile's battery is 95 then it will print Mobile is Charged
or if mobile's Battery is less than 20, it will print Mobile needs Charging
or if mobile's Battery is 50, it will print Mobile is Sufficiently Charged
If...Else With Other Conditional Operators
Example
Here,
I am Introducing the concept of Nested IF...Else, Whenever if...else is used inside another if...else condition then this state is called as Nested if...else.
Let's Understand the Example :
First, We are checking if the mobile is in a charging state or not... here we are using variable mobileBatteryState to know the State.
If Mobile Is Charging then Print Mobile is Charging otherwise it will again check for multiple conditions like:
if mobile's Battery is 100% then it will print Mobile is Completely Charged
if Mobile's Battery is in Between 90 and 100 then it will show Mobile is Charged
if Mobile's Battery is in Between 20 and 90 then it will show Mobile is Sufficiently Charged
or otherwise it will show Mobile needs Charging