View vs Pure in Solidity

pure function cannot read from state or write to state. In functional programming terminology, it is a function that does not have any side-effects.

    // pure function cannot read from state or write to state
    function alwaysOne() public pure returns(int) {
        return 1;
    }

view function can read from state, but can not write to state.

// view function can read from state, but not write to state
    function hello() public view returns(string memory) {
        return message; // message is a state variable in contract
    }

function without view or pure keywords, i.e., a regular function, can both read from and write to state.

 // function without view and pure can both read and write to state
    function readAndWrite() public returns (string memory) {
        message = "Changed it";
        return message;
    }
Show Comments