Functions

Note: This lesson covers defining functions in JavaScript and Python.

Definition

A function is a block of reusable code designed to perform a particular task. The function is executed when it is "called".

Syntax

functions

function function_name(parameter1, parameter2, ... parameterN) {
	block;
}
def function_name(parameter1, parameter2, ... parameterN):
	block	

Examples

Example 1: Without Parameters

A function message() is defined. The parentheses () are empty as this function does not use parameters. This means the function is not passed data to operate on.

When the function is called, i.e., message(), it displays a simple message 'Hello'.

This is a simple example. When you create functions you can optionally define:

  1. Defining a function
    function message() {
    	alert("Hello");
    }
  2. Calling a function
    message();		// Hello
  1. Defining a function
    def message():
    	print("Hello")
  2. Calling a function
    message()			# Hello

Example 2: With Parameters

Here the function will be passed data to operate on. We define a function greet with a parameter named message.

When the function is called, the function assigns the data passed to it, i.e., morning, afternoon or evening to the parameter message. Note the difference between an argument and parameter.

Functions can be defined with a list of parameters by separating each parameter name with a comma.

  1. Defining a function
    function greet(message){
    	alert("Good " + message);
    }
  2. Calling a function
    greet("morning"); 		// Good morning
    greet("afternoon");		// Good afternoon
    greet("evening");		// Good evening
    
  1. Defining a function
    def greet(message):
    	print("Good " + message)
  2. Calling a function
    greet("morning")		# Good morning
    greet("afternoon")		# Good afternoon
    greet("evening")		# Good evening

Example 3: Returning Results

function square(x){
	return x * x;
	alert("this line will never be printed");
}

var result = square(10);
alert(result);
def square(x):
	return x * x
	print("this line will never be printed")

result = square(10)
print(result)

Example 4: Returning Ticket Price

function ticket(age){
	var entry = "";
 	if ( age <= 12 ) {
		entry = "Free";
	} else if ( age <= 16 ) {
		entry = "£10";
	} else {
		entry = "£20";
	}
	return entry;
}

alert(ticket(10));		// Free
alert(ticket(14));		// £10
alert(ticket(21));		// £20
def ticket(age):
	entry = ""
	if age <= 12:
		entry = "Free"
	elif age <= 16:
		entry = "£10"
    else:
		entry = "£20"
	return entry

print(ticket(10))       # Free
print(ticket(14))       # £10
print(ticket(21))       # £20