Bird
Raised Fist0
Blockchain / Solidityprogramming~15 mins

Using for directive in Blockchain / Solidity - Deep Dive

Choose your learning style10 modes available
Overview - Using for directive
What is it?
The 'for' directive is a programming tool used to repeat a set of instructions multiple times. In blockchain development, it helps automate repetitive tasks like processing lists of transactions or iterating over data structures. It works by defining a loop that runs until a certain condition is met, making code more efficient and easier to manage.
Why it matters
Without the 'for' directive, developers would have to write the same code repeatedly for each item, which is slow, error-prone, and hard to maintain. In blockchain, where data and transactions are often handled in batches, loops save time and reduce mistakes. This makes smart contracts and blockchain applications more reliable and scalable.
Where it fits
Before learning the 'for' directive, you should understand basic programming concepts like variables and conditions. After mastering it, you can explore more complex loops, such as 'while' loops, and learn how to combine loops with functions and events in blockchain smart contracts.
Mental Model
Core Idea
A 'for' directive repeats a block of code a set number of times, automating repetitive tasks efficiently.
Think of it like...
Imagine you have a stack of letters to mail. Instead of writing the address on each one separately, you use a stamp machine that automatically stamps each letter as it passes through. The 'for' directive is like that machine, doing the same action repeatedly without extra effort.
┌───────────────┐
│ Initialize    │
│ counter i = 0 │
└──────┬────────┘
       │
       ▼
┌───────────────┐
│ Check i < n?  │
└──────┬────────┘
       │Yes
       ▼
┌───────────────┐
│ Execute block │
│ of code       │
└──────┬────────┘
       │
       ▼
┌───────────────┐
│ Increment i   │
└──────┬────────┘
       │
       └─────► Back to Check
Build-Up - 6 Steps
1
FoundationUnderstanding basic loop structure
🤔
Concept: Introduce the basic parts of a 'for' loop: initialization, condition, and increment.
A 'for' loop starts by setting a counter variable, then checks if a condition is true before each repetition. If true, it runs the code inside the loop, then changes the counter and repeats. For example, in Solidity (a blockchain language): for (uint i = 0; i < 5; i++) { // code to repeat } This runs the code 5 times, with i going from 0 to 4.
Result
The loop runs 5 times, executing the code block each time with i values 0,1,2,3,4.
Understanding the loop's three parts helps you control exactly how many times the code repeats.
2
FoundationUsing loops to process arrays
🤔
Concept: Learn how to use 'for' loops to go through each item in a list or array.
In blockchain, data often comes in arrays. A 'for' loop can visit each element to read or change it. Example in Solidity: uint[] numbers = [10, 20, 30]; for (uint i = 0; i < numbers.length; i++) { numbers[i] = numbers[i] * 2; } This doubles each number in the array.
Result
The array changes to [20, 40, 60] after the loop runs.
Loops let you handle many data items with one code block, saving time and reducing errors.
3
IntermediateControlling loops with conditions
🤔Before reading on: do you think a 'for' loop can stop early using a condition inside it? Commit to your answer.
Concept: Learn how to stop a loop early using 'break' or skip steps with 'continue'.
Sometimes you want to stop looping before reaching the end. Use 'break' to exit the loop immediately. Use 'continue' to skip the current step and move to the next. Example: for (uint i = 0; i < 10; i++) { if (i == 5) { break; // stop loop when i is 5 } if (i % 2 == 0) { continue; // skip even numbers } // code runs only for odd i less than 5 } This loop stops at 5 and only processes odd numbers before that.
Result
Loop runs for i=1,3 and stops before i=5.
Knowing how to control loop flow makes your code more flexible and efficient.
4
IntermediateNested loops for complex data
🤔Before reading on: do you think loops can be placed inside other loops? Commit to your answer.
Concept: Introduce loops inside loops to handle multi-dimensional data or complex tasks.
Sometimes data is like a table with rows and columns. You can use one loop inside another to visit every cell. Example: uint[2][3] matrix = [[1,2],[3,4],[5,6]]; for (uint i = 0; i < 3; i++) { for (uint j = 0; j < 2; j++) { // process matrix[i][j] } } This visits all 6 numbers in the matrix.
Result
All elements in the 2D array are accessed one by one.
Nested loops let you work with complex data structures common in blockchain applications.
5
AdvancedGas cost considerations in loops
🤔Before reading on: do you think loops in blockchain smart contracts have no cost difference based on iterations? Commit to your answer.
Concept: Understand how loops affect transaction costs (gas) in blockchain environments.
Each operation in a smart contract costs gas, which users pay. Loops that run many times increase gas cost linearly. For example, looping over a large array can make a transaction expensive or even fail if gas runs out. Developers must limit loop size or use alternative designs like events or off-chain processing.
Result
Loops with many iterations can cause high gas fees or failed transactions.
Knowing gas costs helps you write efficient, user-friendly blockchain code.
6
ExpertAvoiding infinite loops and reentrancy risks
🤔Before reading on: do you think a 'for' loop can cause security risks in smart contracts? Commit to your answer.
Concept: Explore how careless loops can cause infinite loops or open security holes like reentrancy attacks.
An infinite loop happens if the loop condition never becomes false, freezing contract execution and wasting gas. Also, loops that call external contracts inside can be vulnerable to reentrancy, where attackers exploit repeated calls to drain funds. Best practice is to avoid unbounded loops and carefully design external calls outside loops.
Result
Proper loop design prevents contract freezing and security breaches.
Understanding loop risks is crucial for secure and reliable blockchain smart contracts.
Under the Hood
At runtime, the 'for' directive initializes a counter variable, then repeatedly checks a condition before each iteration. If true, it executes the loop body, then updates the counter. This cycle continues until the condition is false. In blockchain virtual machines like the Ethereum EVM, each instruction consumes gas, so each loop iteration adds to the total cost. The loop variables and state changes are stored in contract storage or memory, affecting execution flow and cost.
Why designed this way?
The 'for' directive follows a simple, clear structure to make loops predictable and easy to understand. Early programming languages adopted this pattern for its readability and control. In blockchain, this design helps developers write deterministic code that behaves the same on all nodes, which is essential for consensus. Alternatives like 'while' loops exist but 'for' loops combine initialization, condition, and increment in one line for clarity.
┌───────────────┐
│ Initialize i  │
│ (i = start)   │
└──────┬────────┘
       │
       ▼
┌───────────────┐
│ Check i < end │
└──────┬────────┘
       │Yes
       ▼
┌───────────────┐
│ Execute body  │
└──────┬────────┘
       │
       ▼
┌───────────────┐
│ Increment i   │
└──────┬────────┘
       │
       └─────► Back to Check
Myth Busters - 3 Common Misconceptions
Quick: Does a 'for' loop always run the same number of times regardless of code inside it? Commit to yes or no.
Common Belief:A 'for' loop always runs the exact number of times specified in its condition.
Tap to reveal reality
Reality:The loop can stop early if a 'break' statement is used or if an error occurs inside the loop.
Why it matters:Assuming fixed iterations can cause bugs or unexpected behavior, especially in smart contracts where early exit affects state and gas.
Quick: Can a 'for' loop in blockchain smart contracts run forever without consequences? Commit to yes or no.
Common Belief:Infinite loops are harmless because the blockchain will just keep running them.
Tap to reveal reality
Reality:Infinite loops waste gas and cause transactions to fail, wasting user funds and blocking contract execution.
Why it matters:Ignoring gas limits can lead to failed transactions and poor user experience.
Quick: Is it safe to call external contracts inside a 'for' loop? Commit to yes or no.
Common Belief:Calling other contracts inside loops is safe and common practice.
Tap to reveal reality
Reality:It can open security risks like reentrancy attacks and increase gas unpredictably.
Why it matters:Not understanding this can lead to contract vulnerabilities and financial loss.
Expert Zone
1
Loops in blockchain must be carefully bounded to avoid exceeding block gas limits, which can cause transaction failures.
2
Using 'memory' arrays inside loops is cheaper than 'storage' arrays, affecting gas optimization strategies.
3
Loop variables and state changes are visible on-chain, so loops can affect contract transparency and auditability.
When NOT to use
Avoid using 'for' loops for unbounded or very large data sets in smart contracts; instead, use off-chain computation or batch processing with multiple transactions.
Production Patterns
In production, developers use 'for' loops to iterate over small arrays like token holders or transaction logs, often combined with events to track progress and avoid gas exhaustion.
Connections
Recursion
Alternative approach to repetition
Understanding loops helps grasp recursion, which repeats tasks by calling functions within themselves, offering another way to handle repeated actions.
Finite State Machines
Loops model repeated state transitions
Loops in code can represent cycles in state machines, common in blockchain contracts managing states like voting or auctions.
Assembly Line Production
Sequential repeated processing
Like an assembly line repeating steps to build products, 'for' loops repeat code steps to process data efficiently.
Common Pitfalls
#1Writing a loop that never ends, causing the contract to freeze.
Wrong approach:for (uint i = 0; i >= 0; i++) { // infinite loop because i will always be >= 0 }
Correct approach:for (uint i = 0; i < 10; i++) { // loop runs 10 times safely }
Root cause:Misunderstanding loop conditions and how counters change leads to infinite loops.
#2Calling external contracts inside a loop without safeguards.
Wrong approach:for (uint i = 0; i < users.length; i++) { externalContract.call(users[i]); }
Correct approach:for (uint i = 0; i < users.length; i++) { // Avoid external calls inside loops or use checks-effects-interactions pattern }
Root cause:Lack of awareness of reentrancy risks and gas cost unpredictability.
#3Looping over large arrays in one transaction causing out-of-gas errors.
Wrong approach:for (uint i = 0; i < largeArray.length; i++) { process(largeArray[i]); }
Correct approach:// Process in smaller batches or off-chain for (uint i = start; i < start + batchSize; i++) { process(largeArray[i]); }
Root cause:Ignoring blockchain gas limits and transaction size constraints.
Key Takeaways
The 'for' directive automates repeating tasks by running code multiple times with controlled start, condition, and increment.
In blockchain, loops must be carefully designed to manage gas costs and avoid security risks like infinite loops and reentrancy.
Loops are essential for processing arrays and complex data structures efficiently in smart contracts.
Understanding loop control statements like 'break' and 'continue' allows flexible and safe iteration.
Expert use of loops balances functionality, cost, and security to build reliable blockchain applications.

Practice

(1/5)
1. What does the for directive do in blockchain programming?
easy
A. Creates a new blockchain transaction
B. Encrypts blockchain data
C. Deletes data from the blockchain
D. Repeats a block of code for each item in a list

Solution

  1. Step 1: Understand the purpose of the for directive

    The for directive is used to repeat code multiple times, once for each item in a list or collection.
  2. Step 2: Relate to blockchain data processing

    In blockchain, it helps process multiple data items like transactions or blocks easily by looping through them.
  3. Final Answer:

    Repeats a block of code for each item in a list -> Option D
  4. Quick Check:

    for directive = repeat code per item [OK]
Hint: For loops repeat code for each item in a list [OK]
Common Mistakes:
  • Confusing for directive with data encryption
  • Thinking for creates or deletes blockchain data
  • Mixing for directive with transaction creation
2. Which of the following is the correct syntax to loop over an array blocks using the for directive?
easy
A. for (let block of blocks) { /* code */ }
B. for (let block in blocks) { /* code */ }
C. for blocks (let block) { /* code */ }
D. loop (block in blocks) { /* code */ }

Solution

  1. Step 1: Identify correct for loop syntax for arrays

    In modern blockchain programming (JavaScript style), for...of loops over array elements directly.
  2. Step 2: Compare options

    for (let block of blocks) { /* code */ } uses for (let block of blocks), which is correct. for (let block in blocks) { /* code */ } uses in which loops keys, not values. Options C and D are invalid syntax.
  3. Final Answer:

    for (let block of blocks) { /* code */ } -> Option A
  4. Quick Check:

    Use for...of to loop array values [OK]
Hint: Use for...of to loop over array items directly [OK]
Common Mistakes:
  • Using for...in to loop arrays (loops keys, not values)
  • Writing invalid loop syntax
  • Confusing loop keywords like loop or for blocks
3. What will be the output of this code snippet?
const blocks = [101, 102, 103];
let result = '';
for (const block of blocks) {
  result += block + '-';
}
console.log(result);
medium
A. 101-102-103
B. 101-102-103-
C. 101102103
D. SyntaxError

Solution

  1. Step 1: Understand the loop operation

    The loop goes through each number in blocks: 101, 102, 103. Each number is added to result with a '-' after it.
  2. Step 2: Trace the string concatenation

    After loop: result = '101-' + '102-' + '103-' = '101-102-103-'
  3. Final Answer:

    101-102-103- -> Option B
  4. Quick Check:

    Concatenate each block with '-' = 101-102-103- [OK]
Hint: Add '-' after each item in loop to get trailing dash [OK]
Common Mistakes:
  • Expecting no trailing dash at the end
  • Confusing for...of with for...in output
  • Thinking output is concatenated without dashes
4. Identify the error in this for loop that processes blockchain transactions:
const transactions = [10, 20, 30];
for (transaction of transactions) {
  console.log(transaction);
}
medium
A. for loop syntax is invalid
B. Incorrect array name
C. Missing declaration keyword for loop variable
D. console.log cannot print transaction

Solution

  1. Step 1: Check loop variable declaration

    The loop variable transaction is used without let or const, which causes a ReferenceError in strict mode.
  2. Step 2: Validate other parts

    Array name and syntax are correct. console.log can print numbers. So only missing declaration is the error.
  3. Final Answer:

    Missing declaration keyword for loop variable -> Option C
  4. Quick Check:

    Declare loop variable with let or const [OK]
Hint: Always declare loop variable with let or const [OK]
Common Mistakes:
  • Forgetting let or const before loop variable
  • Assuming console.log can't print numbers
  • Thinking array name is wrong
5. You have a list of blockchain block heights: [5, 10, 15, 20]. Using a for directive, how do you create a new array with each height doubled?
hard
A. for (let i = 0; i < heights.length; i++) { doubled[i] = heights[i] * 2; }
B. for (heights of doubled) { doubled.push(heights * 2); }
C. for (let h in heights) { doubled.push(h * 2); }
D. for (h of heights) { doubled.push(h * 2); }

Solution

  1. Step 1: Understand the goal and data

    We want to double each number in heights and store in doubled array. heights = [5,10,15,20]
  2. Step 2: Analyze each option

    for (h of heights) { doubled.push(h * 2); } uses for...of but missing let or const declaration for loop variable h, so ReferenceError. for (let i = 0; i < heights.length; i++) { doubled[i] = heights[i] * 2; } uses classic for loop with index to assign doubled[i] = heights[i]*2, which works correctly. for (let h in heights) { doubled.push(h * 2); } uses for...in which loops keys (indexes as strings), so multiplying keys is wrong. for (heights of doubled) { doubled.push(heights * 2); } has invalid syntax (for (heights of doubled)) and reversed arrays.
  3. Final Answer:

    for (let i = 0; i < heights.length; i++) { doubled[i] = heights[i] * 2; } -> Option A
  4. Quick Check:

    Use index loop to assign doubled values [OK]
Hint: Use index loop to fill new array with doubled values [OK]
Common Mistakes:
  • Using for...in to loop array values
  • Not initializing doubled array before pushing
  • Writing invalid loop syntax
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