Comp 110 Local Primitive Variables

Local Primitive Variables

Local primitive variables are variables on the stack that hold a primitive value (of type number, string, or boolean). That takes care of the 'primitive' part of the name, so on now to the 'local' part.

A variable being local means it is defined within a function or frame. If the variable is local, we're more limited in where we can use it. When a variable is declared within a function, it is local to that function. This means it can only be accessed within that function! When we declare a variable within a function, it is created (and can only be used) within that function call's frame. Since we're talking about local primitive variables, we're talking about number, string, or boolean variables, which are stored on the stack. 

When creating a local primitive variable, its name is added to the current frame on the stack. Then, when we assign it a primitive value, we update its value in this frame.  

 Let's take a look:

let num = (): number => {
    let x = 110;
    let y = x;
    y = 4;
    return y;

In this code, we've got a function num. Now we'll think about the local variables. Within this function, we see let x = 110; so we know we'll add the name x within our stack frame for num. Then, we see we're assigning it 110, so x holds the value 110. 

Next, we see let y = x; so we add the name y within num's stack frame. Then we've got the assignment. We assign y a copy of x's value. So, y is assigned 110. Since y is assigned this value, this means y is NOT pointing to x. It is really just holding the actual number 110. 

At the next line, we see y = 4, so we are reassigning y to now hold the value 4. Even though we changed y's value, x is still 110.

Then, we return y so we return 4. Once we've returned, we're done with the function call, and we're done accessing the variables defined within the function.

After this point, we can't use those variables anywhere else. They only existed within num, and we are no longer in num.