Comp 110 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 in which it is defined

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

let course = 101;

       if (course === 110) {
            let welcome = "Welcome to COMP 110!";
       } else {
            print("Should've taken 110");
       }

print(welcome); // ERROR

In the code above, the print(welcome) call would cause an error, because the program is not able to access the welcome variable, as it was declared within the if statement block which we have not accessed.

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

let course = 101;
let welcome = "Let's get ready to rumbleeee!";

       if (course === 110) {
            welcome = "Welcome to COMP110!";
       } else {
            print("Should've taken 110");
       }

print(welcome); //prints "Let's get ready to rumbleeee!"

This would now work! Because we have declared the welcome variable inside the same block as the print call, as well as updating its later in the if block. Welcome can be accessed from either point and the code will run!

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

Variable Shadowing

In blocks of code like the one above, where there is a nested 'inner block,' it is possible to declare a variable with the same name as another variable in the outer block. This is known as variable shadowing. 

Although this will not cause an error, it makes it very tricky to remember which variable is storing which piece of data and what you want each one to do.

Therefore, it is good practice to give your variables meaningful names, so you know exactly why you created them and what you want them to do.

An example of variable shadowing is shown below:

let b = 1485;
print(b); // prints 1485
{
   let b = 1200; // b here is a new variable which is completely independent of the x which storing the number 1485 above
   print(b); // prints 1200
}
print(b); /* prints 1485. This will not print 1200 because the x variable storing 1200 is out of scope - it does not exist as far as this print 
             statement is aware!! */