A full guide to loops in Solidity
In this guide, we are going to learn how to create loops in Solidity and how they work. We're also going to learn how to use the break and continue keywords.
In this guide, we are going to learn how to create loops in Solidity and how they work. We're also going to learn how to use the break
and continue
keywords.
You have 2 ways to create a loop in Solidity, either with for
or with while
Creating a for loop in Solidity
To create a for loop, it works pretty much like in JavaScript:
for (uint256 i = 0; i < 10; i++) {
// do something here
}
And you can break the loop using the break
keyword:
for (uint256 i = 0; i < 10; i++) {
if (i == 2) {
break;
}
// this loop will end when i == 2
}
Or you can skip an iteration with continue
:
for (uint256 i = 0; i < 10; i++) {
if (i == 2) {
continue;
}
// this code will not be reached when i == 2 because of continue
}
Creating while loops
You can also use while
to create loops. It's not recommended though because you can't always know when the condition will stop (if it's ever going to stop).
uint256 i = 0;
while (i < 10) {
// do something here
i++;
}
You can also make a do ... while
loop:
uint256 i = 0;
do {
// do something here
i++;
} while (i < 10);
And that's it 🎉
Thank you for reading this article, if you want to go further and get better at blockchain development, leave your email below and you'll get:
- access to the private Discord of a community of Web3 builders
- access to free guides that will teach you a subject from scratch like the Web3 JS Cheat Sheet