Comp 110 void Functions

void Functions

Sometimes a function returns nothing! Void functions are super helpful when we need to modify variables or objects 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.

Let's take a look at some examples!

1. Mutating arrays

let square = (arr: number[]): void => {
    for (let i: number = 0; i < arr.length; i++) {
        arr[i] = arr[i] * arr[i];
    }
);
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!

2. Working with Objects and Methods

class Car {    
    fuelTankFull: boolean = true;    
    mpg: number = 30;    
    color: string = "blue";
 
    milesDriven = (miles: number): void => {
        if (miles > 100) {
            fuelTankFull = false;
        }
    }
}
let main = () async => {
    let car1: Car = new Car();
    let car2: Car = new Car();
 
    car1.milesDriven(150);
    car2.milesDriven(50);
 
    print(car1.fuelTankFull);
    print(car2.fuelTankFull);
};
 
main();

The resulting output will be false for car 1 and true for car 2Note here that this void method is just a specific type of void function. For a review of methods, check out this page.