The difference between view and pure functions in Solidity

In this guide, we are going to learn what is the difference between view and pure functions in Solidity and what it means to define functions with these keywords

In this guide, we are going to learn what is the difference between view and pure functions in Solidity and what it means to define functions with these keywords.

First of all, smart contracts have that concept of state. Basically, the state of a smart contract corresponds to the values that the properties of the smart contract are set to.

Mutating the properties of a smart contract creates a transaction because it changes the data that is in the blockchain.

That means it costs gas fees to change the variables of a smart contract because you change the data on the blockchain.

Reading data from the blockchain doesn't create new blocks so it doesn't create a transaction and so it costs no gas.

So we have 2 keywords to tell how a function will interact with the state:

  • view means the function reads from the state but doesn't mutate it
  • pure means it doesn't read and doesn't mutate the state
  • and passing nothing means it mutates the state

Functions that use these keywords don't cost any gas to call if they're called externally from outside the contract.

However if they are called internally by another function that uses gas, the gas amount needed will increase.

When it comes to gas cost, you need to have this in mind:

  • Reading data doesn't cost any gas
  • Mutating data costs gas
  • Mutating data and reading data from an external function (of the same smart contract or another smart contract on the blockchain) will cost more gas than just mutating the data

That's it! 🎉

Thanks for reading this article! Feel free to leave your email below to join the community and receive a free guide to learn Web3 JS