Differences between constant and immutable variables in solidity

Immutable variables

The immutable variables are unable to mutate or change after creation. There are two ways to assign any arbitrary value to immutable variables:

  1. At the point of their declaration.
  2. In the constructor of the contract.

Note: The assigned immutables that are declared are considered as initialized only when the constructor of the contract is executing.

Code example

Let's look at the code below:

const hre = require("hardhat");

async function main() {
  await hre.run("compile");

  const Contract = await hre.ethers.getContractFactory("test");
  const contract = await Contract.deploy();

  await contract.deployed();
}

main()
  .then(() => process.exit(0))
  .catch((error) => {
    console.error(error);
    process.exit(1);
  });
Implementation of immutable variable

Code explanation

  • Line 7: We assign the immutable variable at the time of declaration.
  • Line 8: We declare an immutable variable to be assigned inside a constructor.
  • Line 10: We assign the declared immutable variable inside the constructor.

The run.js file is used only for display purposes.

Constant

When using constant variables, the value must be assigned where the variable is declared, and it must be a constant at compile time. The value remains constant throughout the execution of the program thus, any attempt to change the constant value will result in an error.

Note: We can also define constant variables at the file level.

Code example

Let's look at the code below:

const hre = require("hardhat");

async function main() {
  await hre.run("compile");

  const Contract = await hre.ethers.getContractFactory("test");
  const contract = await Contract.deploy();

  await contract.deployed();
}

main()
  .then(() => process.exit(0))
  .catch((error) => {
    console.error(error);
    process.exit(1);
  });
Implementation of constant variable

Code explanation

  • Line 8: We assign a value to the constant variable at the time of declaration.
  • Line 11: We print the value of constant variable using console.logInt().

The run.js file is used only for display purposes.

Difference between constant and immutable variable

State variables could be specified as immutable or constant. In solidity, we use constant to permanently fix a variable value so that afterward, it can’t be altered. A constant variable is assigned a value at the time of declaration. On the other hand, immutable is also used for the same purpose but is a little flexible as it can be assigned inside a constructor at the time of its construction.

Note: Both immutable and constant variables can't be changed once declared.

Copyright ©2024 Educative, Inc. All rights reserved