A function is a block of code which is written and can be reused elsewhere in the program. With functions, you can make your program more readable and modular.
User-defined functions are the ones created by the user. This is what we would be learning in this tutorial.
The codes in this tutorial are tested using Notepad++ as shown below. You can download Notepad++ free from here.
1. Defining a Function
The first step to creating a function is to define it. You can do this using the function keyword, then followed by the function name and a list of parameters in brackets. Then the body of the function enclosed in curly braces.
The syntax is given below
Note that a parameter-list could also be empty.
Let’s now take a real example.
The code below is a function that displays an alert message to the output
2. Calling a Function
Before you can use a function, you need to call it. This is also called invocation. For instance you want the function to run when a button is clicked, when a key is pressed or when any other event occurs.
The following code calls the greetings() function when a button is clicked.
3. Function Parameters
The previous functions we’ve written have been without parameters. But you can pass a parameter to functions when invoking the function. A function can take more than one parameter. Each parameter is separated by a comma.
Now we modify the greetings function to take the name and the age as parameters.
4. The return Statement
The return statement can be used at the end of a function body. When the function needs to return a value, then it is required to use a return statement. However, if no values are returned, then the return statement is optional. For example, if you have a function that takes three numbers and calculates the sum.
The function below takes two parameters: the firstname and the lastname. It then concatenates them and returns the concatenated string.
Note that the outputs of the codes in this tutorial have not been provided. This is to enable you to try it yourself and see what you get. We also recommend watching the video lessons for clarification. Also feel free to ask for help you have any challenges.