Video Tutorial
What is the IF condition?
IF condition in programming is used for making decisions based on the boolean context of the expression i.e if the expression is true then the conditional code is executed.
The programmer can selectively execute code based on the expression.
Characteristics of IF condition
Some of the common attributes are
- IF condition can have a single expression or can be combined with an else statement
if(expression) {
// code
} else {
// code
}
A condition is only executed if it is TRUTHY i.e in a boolean context the expression has to return the value "true"
IF condition can be chained i.e programmer can add multiple "else if" statements
if(expression) {
// code
}else if {
// code
} else if {
// code
} else if {
// code
}
In a chained IF condition "else" statement would be the last instruction if it is used i.e else is optional. If "else" is used in between the chain it is an error.
The expression has to be put within circular braces i.e (expression). If circular braces are not used it is an error.
The code blocks i.e {} (flower braces) for the IF condition can be ignored if there is only one instruction.
let city = "Mysuru";
if (city==="Bengaluru")
console.log("City is Bengaluru");
else if(city==="Mysuru")
console.log("City is Mysuru");
else
console.log("City does not match");
- The code blocks i.e {} (flower braces) for the IF condition are mandatory if more than one instruction is there for the given statement. If not used it is an error.
// if & else with multiple instructions
if (3 > 2) {
console.log("3 is greater than 2");
console.log("if condition");
} else {
console.log("3 is greater than 2");
console.log("3 is less than 2 else statement ");
}
Complete Code Listing
/*
Author : Mahavir DS Rathore
Objectives
--------------------
a. What is - if condition?
b. Syntax and usage
c. Implementation
*/
// if the condition is true -- executed
if (2 > 1 )
console.log("2 is greater than 1");
// if condition & else -- single statements
if (1 > 2 )
console.log("1 is greater than 1");
else
console.log("1 is less than 2");
// if & else with multiple instructions
if (3 > 2) {
console.log("3 is greater than 2");
console.log("if condition");
} else {
console.log("3 is greater than 2");
console.log("3 is less than 2 else statement ");
}
// without using - () - error
// can use - (())
if ((4 > 3)) {
console.log("4 greater than 3")
}
// Not a truthy value
if (0)
console.log("true");
else
console.log("false"); // result - false
// Code block is optional for - single instruction
let city = "Mysuru2";
if (city==="Bengaluru")
console.log("City is Bengaluru");
else if(city==="Mysuru")
console.log("City is Mysuru"); // Result - City is Mysuru
else
console.log("City does not match");