1

I am just starting out with Solidity and I came across this code block meant to deploy a new contract and add the address to an array.

Can someone please explain why the array is initialized this way?

It is different from how I will normally do it in JavaScript

import "./simpleStorage.sol";

// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;



contract StorageFactory {

    SimpleStorage[] public simpleStorageArray;

    function createSimpleStorageContract() public {
       SimpleStorage simpleStorage = new SimpleStorage(); 
       simpleStorageArray.push(simpleStorage);
    }
}

1 Answer 1

0

In Solidity you can initialize an array like SimpleStorageArray[] variable without specify its length. Only for storage arrays, there is a method called push() that allows to add in queue the element inside array.

In your case, when a user interact for the first time createSimpleStorageContract() in SimpleStorage[] array will add an instance of SimpleStorageArray smart contract inside first index about array. When a user call for the second time this function, the SimpleStorage instance will be insert into second index about array, and so on...

More details about arrays here.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.