🎓 A1Learner
🔍
0 of 50 lessons completed

Solidity If Else

An if statement runs different code depending on whether a condition is true. The else if and else parts cover the remaining cases in order.

If, else if, and else pick a band

Scores of 90 or more give band 1, and scores of 50 or more give band 2. Every lower score falls through to band 3.

// SPDX-License-Identifier: MIT
pragma solidity ^0.8.30;

contract GradeBand {
    function band(uint256 score) public pure returns (uint256) {
        if (score >= 90) {
            return 1;
        } else if (score >= 50) {
            return 2;
        } else {
            return 3;
        }
    }
}

If and else make a two-way choice

With only two outcomes, one if and one else are enough. A score of 50 or more passes, and anything lower does not.

// SPDX-License-Identifier: MIT
pragma solidity ^0.8.30;

contract PassCheck {
    function passed(uint256 score) public pure returns (bool) {
        if (score >= 50) {
            return true;
        } else {
            return false;
        }
    }
}

The ternary is the short two-way form

The ternary packs the same two-way choice into one line. It gives 1 for a pass and 0 for a fail.

// SPDX-License-Identifier: MIT
pragma solidity ^0.8.30;

contract PassMark {
    function mark(uint256 score) public pure returns (uint256) {
        return score >= 50 ? 1 : 0;
    }
}

Example

// SPDX-License-Identifier: MIT
pragma solidity ^0.8.30;

contract GradeChecker {
    function band(uint256 score) public pure returns (uint256) {
        if (score >= 90) {
            return 1;
        } else if (score >= 50) {
            return 2;
        } else {
            return 3;
        }
    }

    function passed(uint256 score) public pure returns (bool) {
        return score >= 50 ? true : false;
    }
}

Key points

  • If: a block that runs only when its condition is true.
  • Else if: an extra condition checked only when every earlier condition was false.
  • Else: a block that runs when no earlier condition was true.
  • Order: conditions are checked from top to bottom, and the first true one wins.
  • Ternary: condition ? a : b is a short form that picks a when the condition is true and b when it is false.
  • Use the ternary for a short two-way choice between two values.

In this example, the GradeChecker contract sorts a score into a band with if, else if, and else. A high score returns band 1, a middle score returns band 2, and a low score returns band 3. The passed function then uses the ternary to answer the two-way pass question in one line.

Note

the condition must be a bool, since Solidity does not treat numbers as true or false.

Try it Yourself

Edit the code, then press Run.

Running is simulated · Remix IDE

Exercise

In the band function, what does band(70) return?