Creating functions

Overview

In this module we will consider how to create functions in JavaScript, and to make use of events, which allow us to instigate the use of functions based on user actions. We will also briefly consider events for forms.

If you are already comfortable with the programming concept of creating functions and with HTML forms, please proceed to the next step.

In-depth background from our introductory programming course

Brief review of programming and web concepts: creating functions

A function definition consists of two parts, the header of the function and the body of the function. The header specifies the name of the function, the names of the input parameters and, depending on the programming language, perhaps the data types of the inputs and/or output.

The function body is the program to be executed when the function is calledTo use a function. on particular inputs, the argumentsA value specified as an input to a function. of the function. Substituting the argument values for the parameters in the body of the function, the steps in the function body are then executed.

The impact of the function call on the input will depend on how the function call is executed. In call by value, it is the value of the input, not the input itself, that is manipulated in the function call. In this case, there is no change to the input. On the other hand, in call by reference, the input itself can be changed by the function call. This is only applicable for types of data that can be changed by mutation, that is, for which it is possible to make changes to the values stored for a variable. Such types of data are mutable.

Care needs to be taken in the naming and use of variables in the function body. The best way to supply values to a function is through parameters, not by using global variables (variables that have meaning everywhere). A variable that is defined inside a function, a local variable, has no meaning outside the function call. As such, it is much safer to use than a global variable, which can be modified anywhere in the program, and hence may end up with an unintended value if accidentally used, say, in the body of another function.

Brief review of programming and web concepts: HTML forms

If you are unfamiliar with HTML forms, you can review the module on forms in the Web basics course.