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]; square(x); square(y); square(z); 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 would'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!
Our main function is also a void function, although unlike other void functions we only call main once.