Else If Chains
Part of the Fundamentals section of Coddy's Solidity journey. Lesson 19 of 53.
Use an else if chain when the alternatives have more than two categories. Conditions are tested from top to bottom. The first matching branch runs, and the remaining branches in that chain are skipped.
The statements in this excerpt run inside the provided main function.
uint256 size = 14;
if (size < 10) {
console.log("small");
} else if (size < 20) {
console.log("medium");
} else {
console.log("large");
}Fourteen fails the first check and passes the second. The second branch already knows that size is at least ten, because reaching it means the earlier condition was false. Order the ranges so an earlier broad condition does not hide a later case.
An else-if chain stops after the first matching branch.
Challenge
EasyClassify points: below 40 prints bronze, from 40 through 79 prints silver, and 80 or more prints gold.
The tests pass arguments to main in this order: uint256 points. Each test starts with fresh contract state.
Use console.log for the requested output. Print only the requested values, one per line, with no extra labels unless the task specifies them.
Try it yourself
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.26;
import "forge-std/console.sol";
contract Main {
function main(uint256 points) external view {
// Write your solution here.
}
}This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Fundamentals
Practice on your own: Solidity playground