JavaScript: Functions
What are functions?
In programming, functions are a fundamental part of building a piece of software. They are a way of adding your own commands to the programming environment so that you can extend and build on the core programming language.
A function is a block of code / a set procedure that you can run over and over again from different places in your application. Essentially, a function is a repeatable set of commands that takes some input and produces some output or action or activity. For instance, you might have a function which can multiply two numbers together or a function which reads whether the user is currently pressing a certain button and then move their sprite around the screen.
First, you must define a function. When you define a function, it doesn’t perform any actions at all – it just records the commands you’ve typed in to the function to playback later.
When you want to use a function later, you must call or execute that function. Once you have defined a function, you can use that function as many times as you like later on.
This example shows a very simple function which prints some text to the console. We then call that function 3 times.
// Define the function ‘sayHello’
function sayHello() {
console.log("Hello, World!");
}
// Call our function 3 times
sayHello(); // Print "Hello, World!"
sayHello(); // Print "Hello, World!"
sayHello(); // Print "Hello, World!"Function Parameters
Functions you define can take zero, one or more parameters. Parameters are variables that you provide when you call the function so that you can customise how the function operates. Parameters are given a name which is used during the life of that function and they only exist within the function - once you reach the end of the function, those parameters are destroyed.
Consider the function ‘console.log’ which we have been using to print text to the console to interact with our scripts.
console.log("Message");The console.log function takes 1 parameter, which is the message that you want to print out. You can use the same function any number of times, and inside it JavaScript might do a whole bunch of things with the string you pass - but that’s not important to you. That’s one of the great things about functions - once you have built a function that does something specific, you can share it with others without them needing to know how the internals work.
The following simple function squares a number - ie. it takes a number and multiplies it by itself;
function square(value) {
return value * value;
}You could then use that function elsewhere in your code by simply doing the following;
var a = square(100); // a = (100 * 100) => 10000
var b = square(6); // b = (6 * 6) => 36 Another example is a function which checks whether a user is under 21 or a student. If they meet either criteria, we should print “Discount” to the console - otherwise, we print “No Discount”.
// Define the function ‘hasTrainDiscount’
function checkDiscount(age, isStudent) {
if ( (age < 21) || isStudent ) {
console.log("Discount");
} else {
console.log("No Discount");
}
}
checkDiscount(20, false); // "Discount"
checkDiscount(30, false); // "No Discount"
checkDiscount(30, true); // "Discount"Function return Statement
Functions can also pass a value back to the code which called it. This is really powerful, and it allows you to write functions to calculate certain values or provide certain information. Functions in JavaScript can only return a single variable/value (but you could return an object which contains other values if you needed too).
Note. Whenever code reaches a return statement inside of a function, that function immediately stops running and return the value. No code after the return statement will ever run!
function getDiscount(month, day) {
var discount = 0;
if ( month == "May" || month == "June" ) {
discount = 20;
} else if ( day == "Monday" ) {
discount = 10;
}
return discount;
}
// You can store the value returned from a function in a variable
var hasDiscount = getDiscount("Monday", "July");
console.log( hasDiscount );
// Or you can use it straight away as a parameter to another function
console.log( getDiscount("Tuesday", "May") );Summary: Function Definitions
A standard function definition usually takes the following form;
function functionName(parameterA, parameterB) {
// ... Some Code ...
return value; // Optional
}A function definition starts with the word ‘function’ and is then followed by a unique ‘functionName’ - which is the name you will use to run this function later. Functions then describe zero, one or more parameters in parenthesis and separated by commas. These are options that you should provide the function whenever you use it and you can access these parameters by the names you have given them. They are variables that will exist just for the duration of this function. The actual code for the function is then enclosed in curly brackets { }.
The return statement is optional and can appear anywhere inside of a function. Whenever your code hits a return statement the function will immediately stop running and the code that called the function will resume. If you provide a value to your return statement, this will pass a variable back to the code that called this function. This lets you return the results of a calculation and continue to use them in your program.
Functions: Additional Advice
It is generally considered good practice to keep your functions short so that they only do one thing and do it well. At Paradox we try to keep our functions to 50-60 lines of code at an absolute maximum. It’s not always possible, and we have lots of old code that breaks those rules, but it is something we strive for where we can.
As a side-node - I’ve seen some monster functions of 500+ lines of code. They might not seem so bad at the time, but when you come back to edit them a year later - they are a nightmare to work with. Not only are they confusing to read - but they are often used in a bunch of places in your code, so you don’t really know if making a “little fix” will inadvertantly break something else!
Try to break you code down into logical, re-usable units when building functions.