The immutable variables are unable to mutate or change after creation. There are two ways to assign any arbitrary value to immutable variables:
Note: The assigned immutables that are declared are considered as initialized only when the constructor of the contract is executing.
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);
});immutable variable at the time of declaration.immutable variable to be assigned inside a constructor.immutable variable inside the constructor.The run.js file is used only for display purposes.
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
constantvariables at the file level.
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);
});constant variable at the time of declaration.constant variable using console.logInt().The run.js file is used only for display purposes.
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
immutableandconstantvariables can't be changed once declared.
Free Resources