View Functions
Definition:
In Solidity, a function marked as view indicates that it can read the blockchain state but cannot modify it. In other words, executing a view function will not change any storage variables in the contract.
Use Cases:
- When you need to query contract state without altering it.
- Examples include checking an account’s balance, verifying whether a user has specific permissions, etc.
- Can be executed without spending gas when called off-chain (e.g., using a Web3 client).
Example:
pragma solidity ^0.8.0;
contract Coin {
mapping(address => uint) balances;
function getBalance(address _addr) public view returns (uint) {
return balances[_addr];
}
}
Pure Functions
Definition:
A function marked as pure indicates that it neither reads nor modifies the blockchain state. Pure functions depend entirely on their input parameters and do not interact with the contract’s state in any way.
Use Cases:
- Ideal for mathematical calculations or string manipulations.
- Suitable when you need logic that doesn’t involve the contract’s storage variables.
- Can be executed without consuming gas, regardless of whether it is called on-chain or off-chain.
Example:
pragma solidity ^0.8.0;
contract Math {
function add(uint a, uint b) public pure returns (uint) {
return a + b;
}
}
Key Differences
| Aspect | View Function | Pure Function |
|---|---|---|
| State Access | Can read state | Cannot read or modify state |
| State Modification | ❌ Not allowed | ❌ Not allowed |
| Gas Usage (off-chain) | Free | Free |
| Gas Usage (on-chain transaction) | May consume a small amount | May consume a small amount |
| Typical Use Case | Querying contract state | Calculations / logic independent of state |



