0
0
Blockchain / Solidityprogramming~5 mins

Using for directive in Blockchain / Solidity

Choose your learning style9 modes available
Introduction

The for directive helps you repeat actions for each item in a list or collection. It makes your code cleaner and easier to manage when working with multiple items.

When you want to process each transaction in a list of blockchain transactions.
When you need to display all wallet addresses stored in a smart contract.
When you want to check each block in a blockchain for a specific condition.
When you want to calculate the total balance from multiple accounts.
When you want to log or audit every event emitted by a contract.
Syntax
Blockchain / Solidity
for (let item of collection) {
    // code to run for each item
}

This syntax is common in JavaScript-based blockchain environments like web3.js or scripts interacting with Ethereum smart contracts.

item is each element from collection, one at a time.

Examples
This prints each transaction ID from the list.
Blockchain / Solidity
const transactions = ['tx1', 'tx2', 'tx3'];
for (let tx of transactions) {
    console.log(tx);
}
This adds up all balances and prints the total.
Blockchain / Solidity
const balances = [100, 200, 300];
let total = 0;
for (let amount of balances) {
    total += amount;
}
console.log(total);
Sample Program

This program prints each wallet address with a label.

Blockchain / Solidity
const walletAddresses = ['0x123', '0x456', '0x789'];
for (let address of walletAddresses) {
    console.log(`Wallet address: ${address}`);
}
OutputSuccess
Important Notes

Make sure the collection you loop over is iterable, like an array.

Using for...of is simpler and safer than traditional for loops when you just need each item.

Summary

The for directive repeats code for each item in a list.

It helps process multiple blockchain data items easily.

Use for...of to loop over arrays or collections simply.