View and Pure Functions

View and Pure Functions

Hey, have you ever come across a view function in solidity? This article shows you what they are and what they mean.

What is a view function?

A view function is a read-only function. This function does not change any state variable.

Code Syntax

function functionName() public view returns(){
  return value
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.13;

contract ViewFuntion {
    uint  digit1 = 5;
    uint digit2 = 10;

//do not change!
function test() public view returns (uint){
  return digit1 + digit2;
}
}

What is a pure function?

A pure function does not read or change state variables

Code Syntax

function functionName() public pure returns(){
  return value
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.13;

contract PureFuntion {
    uint  digit1 = 5;
    uint digit2 = 10;

//do not change and read!
function test() public pure returns (uint){
  return digit1 + digit2;
}
}