Comp 110 Primitive Parameters

Primitive Parameters

Primitive parameters are parameters of a function that are of primitive types. This means in a function with parameters, any parameter that has type numberstring, or boolean is a primitive parameter.

When you call a function with parameters, you supply it with arguments. For primitive parameters, the value of the argument you give is assigned to the parameter. Let's get a closer look at what's happening through an example:

import { print } from "introcs";

let x = 4;
let y = 5;
let add = (x: number, y: number): number => {
    x = 2;
    return x + y;
print(add(x, y));

In this code snippet, we have some number variables, a function declaration, and a function call.

When we call add(x, y) we are calling the add function with the first argument as x and the second y. So, we make a new frame on the stack for this function call named add. The value of x (which is 4) is assigned to the parameter x within this frame, and the value of y (which is 5) is assigned to the parameter y that also exists only within the frame

At this point, we have x assigned 4 and y assigned 5. The next line, x = 2;  is updating our local x (the one that is a part of the function add call's frame on the stack) to be 2 now instead of 4. Then, we return x + y returning 2 + 5 which is 7. This function call was inside a print statement so we print 7. We are now done with this function call and also done with the add frame on the stack.

The next line in our program is print(x);

What is printed here?

The key is to know is which x we are referencing. We are no longer executing code within our add function. This means we're now working with the original x variable we had before we even encountered the function call.

Since our add function had number parameters, these parameters were primitive parameters. The value of the argument was copied in for the parameter and used within the function and had NO EFFECT on the original x. 

In the last line of our program when we say print(x); we are going to print 4. We are back outside our add function and talking about our original x, which was defined in the global scope. This value is still 4.

When we were going through the function call and using x and y as arguments, we just copied the values stored in x and y into the parameter. Since we were just copying the value (meaning the actual number stored in the variable), the original variable's value never changed.