Hi @JosephGarza,
Thatâs great youâre enjoying the course and feeling so motivated
Yes, that is a helpful thing to do, because in Solidity there is a lot of overlap with Javascript in terms of syntax, structure and concepts. There are obviously key differences, but already knowing JavaScript certainly helps a lot.
Thatâs great that youâre already thinking in terms of scope. I think that the following is the setNumber() example you are referring to. Please correct me if Iâm wrong.
contract HelloWorld {
int number;
function setNumber(int newNumber) public {
number = newNumber;
}
function getNumber() public view returns(int){
return number;
}
}
int number;
âis a state variable and defined within our contract, and so it is accessible from anywhere within the contract, including within the local scope of the functions i.e. from within the function bodies (what you are calling block scope, but we donât use that term in Solidity).
If we define a variable within a functionâs local scope, then this can only be referenced/accessed locally within that same function.
But in the example above, there is no local variable defined within setNumber(). Instead, this lineâŚ
number = newNumber;
⌠references the number value input as the argument/parameter newNumber
, and assigns it to our number
state variable, where it is stored within the contract state. This line of code within our function can do this, because state variables are accessible from anywhere within the contract. This is similar to how, in JavaScript, variables defined in global scope are accessible from within the block scope of functions (or function scope).
In our example contract, we can then call getNumber() which is able to access the number value input previously, and now stored in the state variable number
, and return this to the caller.
However, what we cannot do is assign newNumber
to a locally defined variable, and then call getNumber() to return it. e.g.
/* THIS CONTRACT WILL NOT COMPILE */
contract HelloWorld {
function setNumber(int newNumber) public {
int number = newNumber;
}
function getNumber() public view returns(int){
return number; // compiler error here
// number is an undeclared identifier
}
}
Values stored in local variables are lost when the function finishes executing, and so cannot then be accessed from within another function afterwards.
I hope that goes some way towards answering your question, or at least allows you to move on. Iâm sure these concepts will become clearer to you over time as you see and work with more examples.
Let us know if anything is unclear, or if you have any further questions