Table of contents
Hello readers, in this article, you are going to learn the difference between view and pure function scope and when to use them.
Let first declare solidity compiler version and then the contract.
pragma solidity ^0.8.10;
contract ViewPure {
}
Where can we use view and pure functions.
View Function
View function can be declared if the code in the function will not modify the state variable. It will only read data from it and not add to it or update it.
Pure function
This is used if the code inside the function does not have anything to do with the state variable.
uint public num;
// Promise not to modify the state.
function addToX() public view returns (uint) {
return num;
}
// Promise not to modify or read from the state.
function add() public pure returns (uint) {
return 1;
}
Le me explain the above code.
State variable num was created with data type uint.
Then function addToX returns the state variable num, that is why we used view function.
Meanwhile, function add return 1 which does not have anything to do with the state variable and that is why we used pure function.
See the full code below.
pragma solidity ^0.8.10;
contract ViewAndPure {
uint public num;
// Promise not to modify the state.
function addToX() public view returns (uint) {
return num;
}
// Promise not to modify or read from the state.
function add() public pure returns (uint) {
return 1;
}
}
Congratulations, you have understood the difference between the view and pure functions.