Function is a block of codes (typically named) which perform a certain process. The motivation of defining a function is to improve reusability and also to encourage better code management.
The most basic form of a function looks like the one defined here.
function display() {
console.log("Good Morning!");
}
This function has a name display. This function does not take any parameter i.e. input and does not return any value after it’s completion. The only lines in the function will display a string message to the console “Good Morning!”
To call this function from within the same script is by it’s name, as shown below.
display();
Which will output the message “Good Morning!” to the console.
What if we need to pass input to function to process? These input to function are called arguments (parameters). So, the next question is – how do we pass arguments to function? Let’s just say we need to define a function that will calculate a total of two numbers, and then it will display the result. The two number will be the arguments to the function.
function calculateTotal(num1: number, num2: number): number {
console.log(num1 + num2);
}
Once we defined the function, we need to call and pass two numbers as arguments.
calculateTotal(10, 9);
To which it will display 19 on the console.
Now, how can we return a value from our function? Can we? Of course we can. To return result from a function, you just use – you guess it right – the “return” keyword. Next, we’re going to update the calculateTotal function to return the total.
function calculateTotal(num1: number, num2: number): number {
return num1 + num2;
}
Since the function now will not display the total but return it instead, the caller of this function must make sure that the return value is assigned to a variable. The final codes to call calculateTotal function and display the result are shown below.
let result = calculateTotal(10, 9);
console.log(Result is ${result});