Modelling



Functions

A function is a set of code that carries out a specifc task

We can think of the function as having:

  1. an input
  2. an engine
  3. an output

image of fucntion


The Engine

We think of the Engine as doing somthing with the input and then producing an output.

In this example, we imagine a function that will calculate the square of the number given to it.

The maths is simple, but this is for a demonstration so that you understand how it works.

  1. the input is 3
  2. an engine calculates 3 * 3
  3. an output is 9

Notice that the function has been given a name and that the input is inside brackets to indicate what it is using for the calculation.

image of fucntion


The Function using Algebra

When writing code, we generalise functions so that they can be used for ANY relevant input.

This is based on algebraic principles where we use named operands with operators to create an equation.

The equation is simple: square = number * number

  1. the input is number
  2. an engine calculates square as number * number
  3. an output is number

Now it does not matter what number we give to the function because the engine is using names for the operands - just like algebra.

image of fucntion


The Function as JS Code

Here is how the code for the function is written in JS.

This is based on algebra where we use named operands with operators to create an equation.

The equation is simple: square = number * number

  1. the keyword function is used to identify the block of code
  2. the function has a name with no spaces in it
  3. The input to the function is put into round brackets and is also a name. This is called a parameter for the function
  4. The code for the function is enclosed in curly brackets { }
  5. the function creates a variable using the name square
  6. the keyword return indicates the output of the function

image of fucntion


Running the Function

Here is how the code for MAIN routine and SUBROUTINE are written in JS.

The concept is that there is a controlling MAIN routine which calls a SUBROUTINE

image of fucntion
image of fucntion

This video shows the order in which the program is executed.