Functions and Subroutines

A function or subroutine is a way to separate sections of code which allows us to organise our code and execute the code multiple times with slight variations and differences. Different programming languages have different words for this; functions, subroutines, methods, etc. They will effectively mean the same thing and refer to the same thing.

All functionals must have a name, as we need to refer to it within the code. They also have optional return types and optional paramaters. A return type of a function is what value we get back from the function, paramaters are what values we give the function to run. A function may not return anything, and it may not have any parameters either.

Strict programming languages enforce that you must declare what variable type, or data type, the return value will be of a function, and also what the parameters have to be. Other languages may not enforce these rules, and thus allow you to send any variable types to a function as parameters or return differnt variable types based on some logic within the function.

The bit that trips up most new developers is that when you create a function it does not execute any code. You must call the function elsewhere in the code to execute the code held within the function.

Below is some example code that shows a function without a return type, and without any parameters.

function myFunction(){

All this function does is print the word “Hello”. However, remember that you must call a function, so it is only because of line number 4 that the code is executed. If you removed the call the function then the code would not be executed.

Below is an example of a function with parameters and a return type

function multiply(a, b){
    var c = a * b;
    return c;
var result = multiply(2, 4);

The first line in the code above defines a function called ‘multiply’ that takes two variables called ‘a’ and ‘b’ respectively. Line numbers 2, inside the function, defines a new variable called ‘c’ that is the result of multipling the two parameters together. Line 3 then return this new variable to the calling code. On line 5 we are creating a variable called ‘result’ and setting its value to the return value of the function. We then print the result, in this instance the result is the number 8.

Leave a Reply