Bird
Raised Fist0
Blockchain / Solidityprogramming~15 mins

If-else statements in Blockchain / Solidity - Deep Dive

Choose your learning style10 modes available
Overview - If-else statements
What is it?
If-else statements are a way to make decisions in a program. They check if a condition is true or false, then run different code based on that. This helps the program choose what to do next. It is like asking a question and acting on the answer.
Why it matters
Without if-else statements, programs would do the same thing all the time, no matter what. This would make blockchain contracts and apps unable to react to different situations, like checking if a user has enough tokens before sending money. If-else lets programs be smart and flexible.
Where it fits
Before learning if-else, you should know what variables and basic expressions are. After if-else, you can learn about loops and functions to make programs more powerful and reusable.
Mental Model
Core Idea
If-else statements let a program choose between two or more paths based on conditions.
Think of it like...
It's like a traffic light that tells cars to stop or go depending on the color. The program checks the 'light' and decides what to do next.
┌───────────────┐
│ Check condition│
└──────┬────────┘
       │True
       ▼
  ┌───────────┐
  │ Run 'if'  │
  │  block    │
  └───────────┘
       │
       ▼
     End
       ▲
       │False
  ┌───────────┐
  │ Run 'else'│
  │  block    │
  └───────────┘
Build-Up - 6 Steps
1
FoundationUnderstanding basic condition checks
🤔
Concept: Learn how to write a simple condition that checks if a value meets a rule.
In blockchain programming, you often check if a number is greater than another. For example, checking if a user's balance is more than 10 tokens. This uses comparison operators like >, <, ==.
Result
You can write expressions that return true or false, like 'balance > 10'.
Understanding how to check conditions is the base for making decisions in code.
2
FoundationWriting a simple if statement
🤔
Concept: Use an if statement to run code only when a condition is true.
Example in Solidity (a blockchain language): if (balance > 10) { // allow transfer } This means the code inside runs only if balance is more than 10.
Result
Code inside the if block runs only when the condition is true.
Knowing how to run code conditionally lets your program react to different states.
3
IntermediateAdding else for alternative actions
🤔Before reading on: do you think else runs when the if condition is true or false? Commit to your answer.
Concept: Use else to run code when the if condition is false.
Example: if (balance > 10) { // allow transfer } else { // reject transfer } If balance is not more than 10, the else block runs.
Result
One of the two blocks runs depending on the condition.
Using else ensures your program handles both yes and no cases clearly.
4
IntermediateUsing else if for multiple choices
🤔Before reading on: do you think else if can check more than one condition in order? Commit to your answer.
Concept: Use else if to check several conditions one after another.
Example: if (balance > 100) { // VIP transfer } else if (balance > 10) { // normal transfer } else { // reject transfer } The program checks each condition in order until one is true.
Result
The first true condition's block runs; others are skipped.
Chaining conditions lets your program choose from many options, not just two.
5
AdvancedNested if-else for complex decisions
🤔Before reading on: do you think nested if-else can make decisions inside decisions? Commit to your answer.
Concept: Put if-else statements inside other if-else blocks to handle detailed cases.
Example: if (balance > 10) { if (isVerified) { // allow transfer } else { // require verification } } else { // reject transfer } This checks verification only if balance is enough.
Result
Decisions can be layered to handle complex rules.
Nesting lets your program handle detailed and dependent conditions step by step.
6
ExpertGas cost and short-circuiting in if-else
🤔Before reading on: do you think all conditions in if-else chains always run? Commit to your answer.
Concept: In blockchain, conditions cost gas (money) to check; if-else stops checking once a true condition is found.
Example: if (balance > 1000) { // expensive check } else if (balance > 10) { // cheaper check } Only the first true condition runs, saving gas. Writing conditions from most likely to least saves money.
Result
Efficient if-else ordering reduces transaction costs.
Knowing how if-else short-circuits helps write cheaper, faster blockchain code.
Under the Hood
When the program reaches an if-else statement, it evaluates the condition inside the if first. If true, it runs the code inside that block and skips the rest. If false, it checks else if conditions in order or runs the else block if no conditions are true. This decision-making happens step-by-step during execution, controlling the program flow.
Why designed this way?
If-else was designed to let programs make choices like humans do, with simple yes/no questions. It avoids running unnecessary code by stopping at the first true condition, which is important in blockchain to save gas and keep transactions efficient.
Start
  │
  ▼
[Evaluate condition]
  │
  ├─True─►[Run if block]─►End
  │
  └─False─►[Check else if or else]
            │
            ├─True─►[Run else if block]─►End
            │
            └─False─►[Run else block]─►End
Myth Busters - 4 Common Misconceptions
Quick: Does else run when the if condition is true? Commit yes or no.
Common Belief:Else runs after if no matter what.
Tap to reveal reality
Reality:Else runs only if the if condition is false.
Why it matters:Running else when if is true causes wrong program behavior and bugs.
Quick: Can multiple if blocks run in a chain of if-else if-else? Commit yes or no.
Common Belief:All if and else if blocks run if their conditions are true.
Tap to reveal reality
Reality:Only the first true condition's block runs; others are skipped.
Why it matters:Expecting multiple blocks to run can cause logic errors and unexpected results.
Quick: Does nesting if-else mean the inner if runs regardless of outer if? Commit yes or no.
Common Belief:Inner if-else always runs even if outer if is false.
Tap to reveal reality
Reality:Inner if-else runs only if the outer if condition is true and its block executes.
Why it matters:Misunderstanding nesting leads to wrong assumptions about code execution paths.
Quick: Do all conditions in if-else chains always get evaluated? Commit yes or no.
Common Belief:Every condition in if-else chains is checked every time.
Tap to reveal reality
Reality:Evaluation stops at the first true condition (short-circuiting).
Why it matters:Ignoring short-circuiting can cause inefficient code and higher blockchain gas costs.
Expert Zone
1
Ordering conditions from most to least likely true saves gas and improves performance in blockchain.
2
Using nested if-else can increase code complexity and gas cost; sometimes combining conditions is better.
3
Short-circuiting behavior can be leveraged to avoid expensive checks when simpler conditions fail.
When NOT to use
If-else is not ideal for many repeated checks or complex state machines; use switch statements or mapping structures instead for clarity and efficiency.
Production Patterns
In smart contracts, if-else is used to validate user permissions, check balances, and enforce rules before executing transactions, often combined with require statements for safety.
Connections
Boolean Logic
If-else statements rely on boolean logic to decide true or false conditions.
Understanding boolean logic helps write clearer and more accurate conditions in if-else statements.
Decision Trees (Data Science)
If-else chains resemble decision trees that split data based on conditions.
Seeing if-else as a decision tree helps understand complex branching and multiple condition handling.
Human Decision Making (Psychology)
If-else mimics how humans make choices by evaluating conditions and picking actions.
Recognizing this connection shows how programming models real-world thinking processes.
Common Pitfalls
#1Writing else without if causes syntax errors.
Wrong approach:else { // code }
Correct approach:if (condition) { // code } else { // code }
Root cause:Else must always follow an if; forgetting this breaks the program.
#2Using = instead of == in condition causes assignment, not comparison.
Wrong approach:if (balance = 10) { // code }
Correct approach:if (balance == 10) { // code }
Root cause:Confusing assignment (=) with equality check (==) leads to wrong logic and bugs.
#3Not covering all cases leads to unexpected behavior.
Wrong approach:if (balance > 10) { // allow } // no else block
Correct approach:if (balance > 10) { // allow } else { // reject }
Root cause:Missing else means program does nothing when condition is false, causing errors.
Key Takeaways
If-else statements let programs choose actions based on conditions, making code flexible and smart.
Only one block in an if-else chain runs: the first true condition's block, or else if none are true.
Nesting if-else allows detailed decisions but can increase complexity and cost in blockchain.
Short-circuiting in if-else saves resources by stopping checks early, important for blockchain efficiency.
Common mistakes include confusing assignment with comparison and missing else blocks, which cause bugs.

Practice

(1/5)
1.

What does an if-else statement do in a blockchain smart contract?

easy
A. It chooses between two actions based on a condition.
B. It repeats a set of instructions multiple times.
C. It stores data permanently on the blockchain.
D. It creates a new blockchain network.

Solution

  1. Step 1: Understand the role of if-else

    An if-else statement checks a condition and decides which code to run next.
  2. Step 2: Apply to blockchain context

    In smart contracts, it helps decide actions like approving transactions or rejecting them.
  3. Final Answer:

    It chooses between two actions based on a condition. -> Option A
  4. Quick Check:

    If-else = choose action [OK]
Hint: If-else picks one path out of two based on condition [OK]
Common Mistakes:
  • Confusing if-else with loops
  • Thinking if-else stores data
  • Believing if-else creates blockchains
2.

Which of the following is the correct syntax for an if-else statement in Solidity?

uint balance = 100;
easy
A. if (balance > 50) then { /* code */ } else { /* code */ }
B. if balance > 50 then { /* code */ } else { /* code */ }
C. if balance > 50: { /* code */ } else: { /* code */ }
D. if (balance > 50) { /* code */ } else { /* code */ }

Solution

  1. Step 1: Recall Solidity if-else syntax

    Solidity uses parentheses around conditions and braces for code blocks without 'then'.
  2. Step 2: Compare options

    Only if (balance > 50) { /* code */ } else { /* code */ } matches Solidity syntax: if (condition) { } else { }.
  3. Final Answer:

    if (balance > 50) { /* code */ } else { /* code */ } -> Option D
  4. Quick Check:

    Solidity if-else = parentheses + braces [OK]
Hint: Solidity if-else uses parentheses and braces, no 'then' [OK]
Common Mistakes:
  • Using 'then' keyword
  • Missing parentheses around condition
  • Using colons instead of braces
3.

What will be the output of this Solidity function when amount = 150?

function checkAmount(uint amount) public pure returns (string memory) {
  if (amount > 100) {
    return "Large amount";
  } else {
    return "Small amount";
  }
}
medium
A. Compilation error
B. "Small amount"
C. "Large amount"
D. No output

Solution

  1. Step 1: Check the condition with amount = 150

    Since 150 > 100, the if condition is true.
  2. Step 2: Determine which return runs

    The function returns "Large amount" because the if branch runs.
  3. Final Answer:

    "Large amount" -> Option C
  4. Quick Check:

    150 > 100 -> "Large amount" [OK]
Hint: Check condition value to pick correct return [OK]
Common Mistakes:
  • Confusing greater than with less than
  • Assuming else runs when if is true
  • Expecting syntax errors
4.

Find the error in this Solidity snippet:

function checkBalance(uint balance) public pure returns (string memory) {
  if balance > 0 {
    return "Positive";
  } else {
    return "Zero or Negative";
  }
}
medium
A. Missing parentheses around the if condition
B. Missing semicolon after return statements
C. Incorrect return type
D. Missing else keyword

Solution

  1. Step 1: Check if statement syntax

    In Solidity, the condition must be inside parentheses: if (condition).
  2. Step 2: Identify the error

    The code has if balance > 0 without parentheses, causing a syntax error.
  3. Final Answer:

    Missing parentheses around the if condition -> Option A
  4. Quick Check:

    if condition needs parentheses [OK]
Hint: Always put condition inside parentheses in if [OK]
Common Mistakes:
  • Omitting parentheses in if condition
  • Thinking semicolons are missing after return
  • Confusing return type errors
5.

You want to write a Solidity function that returns "Access granted" only if userRole is exactly "admin", otherwise returns "Access denied". Which code snippet correctly uses if-else to do this?

hard
A. if (userRole = "admin") { return "Access granted"; } else { return "Access denied"; }
B. if (userRole == "admin") { return "Access granted"; } else { return "Access denied"; }
C. if userRole == "admin" { return "Access granted"; } else { return "Access denied"; }
D. if (userRole.equals("admin")) { return "Access granted"; } else { return "Access denied"; }

Solution

  1. Step 1: Understand string comparison in Solidity

    Solidity uses == to compare strings for equality, not = or methods like equals().
  2. Step 2: Check syntax correctness

    if (userRole == "admin") { return "Access granted"; } else { return "Access denied"; } uses == with parentheses and braces correctly.
  3. Final Answer:

    if (userRole == "admin") { return "Access granted"; } else { return "Access denied"; } -> Option B
  4. Quick Check:

    Use == for string comparison in if [OK]
Hint: Use == to compare strings in Solidity if conditions [OK]
Common Mistakes:
  • Using single = instead of ==
  • Omitting parentheses in if
  • Using Java-style equals() method
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard