View Vs Pure Function in Solidity | Solidity Basics

·

2 min read

In this article we are going to learn what is View and Pure function in Solidity. I will also give examples which will clear the concept even more.

Let's Start..

What is Pure Function?

When a function is declared as Pure then function will neither read the data nor will change/write the data of the state variables.

Wondering what state variables are?

State variables are the variables which are declared outside the function and obviously inside the contract.

Also we have Local variables which are declared inside the function.

I hope you now know what Pure function is.

But still if you are facing any doubt, no worries. We will take one example to clear concept.

// SPDX-License-Identifier: GPL-3.0

pragma solidity >= 0.5.0 < 0.9.0;

contract WagmiGeeks{

    uint public age = 10; // state variable

    // pure function -> No Read/Write from state variables
    // Below function will not read/take any data from
    // any state variables nor it will write/change 
    // any data in state variable
    function pureFunction() public pure returns(uint){
        uint num = 10; // num is local variable
        return num;
    }
}

What is View Function?

As the name suggests, it will just view the state variables meaning it will just read the data from the state variables but it cannot change/write the data of the state variables.

Now let's take one example of View Function.

// SPDX-License-Identifier: GPL-3.0

pragma solidity >= 0.5.0 < 0.9.0;

contract WagmiGeeks{

    uint public age = 10; // state variable

    // view function -> Only read from state variables
    // Below function will take data from
    // state variables (in this case "age") but it will
    // not write/change any data in state variable
    function viewFunction() public view returns(uint){
        uint readAge = age; // readAge is local variable
        return readAge;
    }

}

Summary

Pure Functions -> No Read/Write from state variables.

View Functions -> Only Read from state variables.

I hope you got the difference between Pure Function and View Function.

Thank You!