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, all of our globals are x, main and sum. 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. This is because 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.