Comp 110 Void Functions

Void Functions

Sometimes a function returns nothingVoid functions are helpful when we need to modify variables in our program, especially when we may need to make these same changes over and over again. Void functions allow us to make use of code that may not produce a return value but is still nonetheless pivotal to our program's execution.

Even though void functions don't return anything, they can have parameters. 

Let's take a look an example!

let angryDwight = (complaint: string): void => {
   print("MICHAEL!" + " " + complaint);
};

Our main function is also a void function, although unlike other void functions we only call main once.

Mutating Arrays

One reason we may want to use a void function is to change an array. 

Let's see the example below

// our void function
let square = (arr: number[]): void => {
    for (let i: number = 0; i < arr.length; i++) {
        arr[i] = arr[i] * arr[i];
    }
};

// this is our main function
let main = () async =>
    let x: number[] = [1, 2, 3];
    let y: number[] = [4, 5, 6];
    let z: number[] = [7, 8, 9];
 
    x.square();
    y.square();
    z.square();
 
    print(x);
    print(y);
    print(z);
};
 
main();

The resulting output to the screen will be:

1, 4, 9

16, 25, 36

49, 64, 81.

If we didn't make use of this void function, we could've had to rewrite the same loop 3 times to process each one of our arrays. This example highlights how void functions reduce redundancy in our code!

Void functions in OO-programming

Another good time to use void functions is when we're working with the properties of an object inside its class, because we don't need to return anything as the class already has access to those fields.

Example:

class Salesman { 
    isEmployeeOfTheMonth: boolean = false;  
    numberOfSales: number = "0";   
}
let receivesSalesAward = (employee: Salesman): void => {
    if (numberOfSales > 50) {
        isEmployeeOfTheMonth = true;
    }
}
let main = () async => {
    let jim: Salesman = new Salesman();
    jim.numberOfSales = 63;
 
    receivesSalesAward(jim);
 
    print(salesman1.isEmployeeOfTheMonth);
};
 
main();

The resulting output will be true for jim.