Comp 110 Global Variables

Global Variables

A global variable is a variable in our program that has a global scope. This means that it is visible and usable throughout the entirety of our program. The global state or global environment is just the set of all global variables available to us in our program.

let x = 0;
let main = async () => { 
    let x = 2;
    let b = 4;
    sum(x, b);
};
export let sum = (x: number, y: number): number => {
    return x + y;
};
main();

In this program, x, main, and sum are all part of globals. Although we don't usually think of functions as being variables, they are included as part of our global environment.

When a local variable has the same name as a global variable, the global variable is shadowed. This means that the value of the global variable is ignored when working with a variable of the same name in a local scope. Let's look at the same example from before:

let x = 0;
let main = async () => { 
    let x = 2;
    let b = 4;
    sum(x, b);
};
export let sum = (x: number, y: number): number => {
    return x + y;
};
main();

The result of calling sum(x,b) will be 6. This is because the global variable x whose value is 0 is shadowed by the value of x inside of main. The call to sum occurs inside of the main function, so we will first check if there is an x available to us inside of main before we go looking for a global x.

If our program had looked something like this:

let x = 0;
let main = async () => {     
    let b = 4;
    sum(x, b);
};
export let sum = (x: number, y: number): number => {
    return x + y;
};
main();

The result of sum(x, b) is 4 since there is no x declared inside main, we use the global variable x, which is initialized to 0.

The Global Frame

We can now incorporate the globals frame onto our stack in our environment diagrams! Function definitions and global variables are bound in this frame. This frame is established before any other function frames on the call stack and acts like any other frame when definitions are reached.

A program begins with an empty stack and heap. The top-most frame on the stack is called the Globals frame. Like we said before, any variable declared in the global frame are global variables.

When a function definition is encountered, add its name to the globals frame connected to a shorthand 'fn' on the heap with start end lines. When a function call is encountered, a new frame is added to the stack and any parameters passed to the function are added too. 

How do you know what the value of a variable is? Always look in the current frame first for the name of the variable. If its not there, then we can now look in globals to determine the value!