# How to initialize a state variable using constructor in solidity.

Constructor is a  special keyword used in solidity for initializing state variables, in this article we will look at what constructor is and how to initialize a state variable with it.





![Table of content(2).png](https://cdn.hashnode.com/res/hashnode/image/upload/v1643387319639/TjFxNk0Uy.png)




## **State variable **

This is a type of variable in solidity , that can be accessed from anywhere inside the contract in which they are being declared.  

This is an example of a state variable below



![Snap(9).png](https://cdn.hashnode.com/res/hashnode/image/upload/v1643387346063/S-SnNTFlS.png)



## **Constructor**

Constructor is a special keyword in solidity , it is use for initializing state variable inside a contract. 
In a contract you can only have a single constructor and even in a situation whereby a constructor is not added to a contract it is being added by default.



A constructor is being created with the syntax below.


![Snap(10).png](https://cdn.hashnode.com/res/hashnode/image/upload/v1643387371414/fsjuBoMT0.png)


## **How to initialize a state variable with Constructor**

State variables can be initialized by a constructor using the following steps :

 (1) declare the constructor keyword 

    
![Snap(12).png](https://cdn.hashnode.com/res/hashnode/image/upload/v1643387396721/voV9fx_EJ.png)

(2) open a parenthesis and pass an argument based on the data types of the state variable

      
![Snap(13).png](https://cdn.hashnode.com/res/hashnode/image/upload/v1643387429468/-uU3BqO4G.png)

(3) Set the scope of the constructor (this can either be public or internal)

   
![Snap(14).png](https://cdn.hashnode.com/res/hashnode/image/upload/v1643387449043/KfiFfo3ec.png)

(4) open a curly brackets to assign the state variable to the arguments of the constructor
      
![Snap(15).png](https://cdn.hashnode.com/res/hashnode/image/upload/v1643387462195/AL7-zT1JU.png)

This is a simple step on how to initialize a state variable using constructor , so whatever value that is input inside the constructor argument is the value of the state variable.



My name is eibrahim a blockchain developer and technical writer , i create content and articles to simplify web 3 and blockchain for everyone. Thanks for reading through

You can follow me on [Twitter](https://twitter.com/hackEibrahim) and [Hashnode](hashnode.com/@hackEibrahim) for more simplified  blockchain content




