Comp 110 Variable Scope

Scope

Scope refers to the visibility of a variable in your code. In other words, which parts of a program can use a particular variable. The simple rule to remember is: a variable can only be referenced from within the same code block that it is defined in

Each code block is grouped together by a set of curly braces. For example:

let sum = (x: number, y: number): number => {
     let result: number;
     result = x + y;
     return result;
};
sum(1, 2);
print(result); //ERROR!

In the code above, calling the sum function would return the sum value, however when print(result) is called, the program is not able to access result since it was declared within the sum function.

So how can we fix this? Let's look at another example:

let result: number;
let sum = (x: number, y: number): number => {
     result = x + y;
     return sum;
};
sum(1, 2);
print(result); // 3 is printed

In the code above, print(result) is valid because sum was declared outside of the block, therefore it is accessible.

This rule applies to function blocks, if-then-else blocks, for/while loop blocks, etc.