if/else statements in Solidity are very similar to JavaScript or other programming languages. It includes an if statement and optionally multiple else if statements and finally an optional else statement. Solidity also supports the ternary operator, which is useful for a quick check that can be done within one line of code. However, it might hurt the readability of the code if it's used extensively.
The following if/else statement returns a string based on the number passed to the function. One of the three strings is returned: smaller than three, bigger than ten or between three and ten.
// SPDX-License-Identifier: MIT
pragma solidity ^0.8;
// if else statements in Solidity
contract IfElse {
function ifElse(uint number) external pure returns (string memory) {
if (number < 3) {
return "smaller than three";
}
else if (number > 10) {
return "bigger than ten";
}
else {
return "between three and ten";
}
}
}
It is also possible to omit the last else statement.
ternary operator
The ternary operator is useful for very short if/else statements. It is a shorthand way of writing the same statement in its full form as shown below. The ternary operator can also be used for two or more conditions, however, the readability of the code suffers so it is better to keep statements with the ternary operator short.
// SPDX-License-Identifier: MIT
pragma solidity ^0.8;
// ternary operator in Solidity
contract IfElse {
// same functionality as function sameStatement but much shorter
function ternary (uint number) external pure returns (bool) {
return number < 3 ? true : false;
}
function sameStatement (uint number) external pure returns (bool) {
if (number < 3) {
return true;
}
else {
return false;
}
}
}