89DEVs

while loop in Solidity

while loop in solidityThe while loop in Solidity is similar to other programming languages like JavaScript. The purpose of this type of loop is to execute as long as the condition is true. As soon as the condition becomes false, the loop is broken. 

The big difference between JavaScript and Solidity is that loops are expensive and can consume a lot of gas. It is good practice to keep the use of loops to a minimum to save gas costs and make the execution of the smart contract more efficent.

There is also a similar loop that is very closely related to the while loop but checks the condition at the end of the iteration instead of the beginning. It is called do ... while loop and has the do statement before the while condition.

Another kind of loop in Solidity is the for loop, which is also known in other programming languages. The main difference is that the incrementation is done within the for statement.

The syntax of the do ... while loop:


// syntax of do ... while loop in Solidity
do {
    // statement to be executed as long as condition is true
} while (condition);


The syntax of the while loop: 


// syntax of while loop in Solidity
while(condition) {
    // statement to be executed as long as condition is true
}



The example below shows a while loop that runs while n is smaller than 10. As soon as n is not smaller than ten anymore, the loop breaks.


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

// while loop in Solidity

contract WhileLoop {

    function exampleWhile() external pure {

        uint n = 0;

        while (n < 10) {
            // code here
            n++;
        }

    }

}