Comp 110 The 'Main' Function

What is the "Main" Function?

The main function, by convention, is the function that starts your program! It is formatted similarly to any other function definition (see below), and is used to call the other functions in the program! You can think of calling main as being similar to turning your key in the ignition - it is what starts the engine of your program to get things running!

The main function does look a little different than the functions we are used to writing, but don't overthink it - it works essentially the same! We have a function definition and function body just as outlined in Functions, however we are lacking parameters and a return statement. This is ok! When main() is called, the code in the function body executes, and then thats it! The only difference is that no value is returned. 

Below are a couple examples of how the main function can be used:

import { print } from "introcs";
//function definition
export let main = async () => {
     print("hello, world");
};
//function call
main();
//when main() is called, all of the code within the main function definition will execute
//in this case, "hello world" will print in the browser!
import { print } from "introcs";
//function definition of introduceMyself
let introduceMyself = (myName: string): string => {
     if(myName === "Kris"){
          return "Hello! I am your professor, " + myName + "!";
     } else {
          return "Hello! I am one of your UTAs, " + myName + "!";
     }
}
//function definition of main function
export let main = async () => {
     print(introduceMyself("Kit"));
};
//function call
main();
//when main() is called, all of the code within the main function definition will execute
//in this case, introduceMyself is called with the argument "Kit"
//"Hello! I am one of your UTAs, Kit!" will print as the main function executes