Like any programming language, Solidity provides most of the control and conditional expressions that are provided by Javascript.
It does not have support for switching and goto in if the conditional expression
It provides the following features
- if-else
- if-else if
Solidity If the else conditional statement
if-else conditional statements are used to execute statements based on conditional expressions.
Syntax
if (conditional expression){
//if code block executed
}
else{
//else code block executed
}
if conditional expression
is true
, if code block executed, else code block executed.
pragma solidity ^0.5.0;
contract SolidityTest {
uint age; // variable
constructor() public {
age = 60;
}
function checkAge() public view returns(string memory) {
if( age > 60) {
return "60";
} else {
return "less than 60";
}
return "default";
}
}
Output:
0:string: less than 60
Solidity if else if conditional expressions
This is an advanced to basic if-else expression.
It uses to test multiple conditions if and else expressions.
if (conditional expression1){
//block 1 executed
}
else if (conditional expression2){
//block 2 executed
}
else{
//else code block executed
}
conditional expression1 is true, block 1 code executed
conditional expression2 is true, block 2 code executed else block will be executed if both conditions are false.
Here is an example of if-else if conditional expression example
pragma solidity ^0.5.0;
contract SolidityTest {
uint age; // variable
constructor() public {
age = 25;
}
function checkAge() public view returns(string memory) {
if( age < 60) {
return "Less than 60";
} else if( age > 60) {
return "Greater than 60";
}
return "default";
}
}
0:string: Less than 60