Functions

Functions are a way of grouping together a set of commands that you want to run as a block to perform some task or other. You may for example wish to calculate temperature in celsius from a value in fahrenheit. You don't want to write the formula again and again but to have it stored away so you can call it when needed.

Functions use the curly bracket syntax we have seen with if, while and for. We use the function keyword, give the function a name and then follow it with the curly braces.

function myFunkyName(){
// run code
}

An example would be:

function doSomething(){
	console.info('Called');
}

Call the Cops

Functions need to be called to be of any use. To call a function we call it by its name followed by parenthesis (brackets) for example:

function doSomething(){
	console.info('Called');
}
doSomething();

JSFIDDLE Demo

Some Notes on Names

We all know someone with a stupid name. You are the parent of these poor old functions so please be kind and give them nice suitable names - something you would be happy to shout in the park.

Some rules first - don't start with numbers, don't use white space.

Some hints try camel casing - that is join more than one word together and capitalise the second word ie camelCase, monkeyBusiness, speedDating.

You may also find it useful to use verb Noun or should I say verbNoun. For example getWeight, calcPrice, moveItem, eatLead.

Parameters

Functions can do stuff and can also be sent stuff to do stuff with. This stuff we call parameters. Parameters are like stuffing a turkey. Try:

function saySomething(words){
	console.info(words);
}
saySomething("Hello Wally");

The function is now set to receive a parameter that we decided to call words. Our function call passes a value to the saySomething function which is a string (it is in quotes). Our simple function will output this value back to the console.

Return to Sender

Functions can also return a value to the sender (the function call). We'll return to the temperature convertor example. I am sure you know this already but to save you embarrassment the formula to convert fahrenheit to celsius is:

Celsius = (Fahrenheit - 32) × 5/9

We could put this logic into a function as follows:

function calcTemp(fah){
	var cel = (fah -32) * 5/9;
	return cel;
}
console.info(calcTemp(61));

The calcTemp function is called but sent a value in its parameters of 61. The calcTemp takes this value and assigns it to the variable fah. This is then used in the calculation to create a variable cel. The return keyword is then used to pass this value back to the original function call. As the original function call is placed inside the console.info then the console outputs the results - that is 16.11111.

Variable Scope and Functions

One feature of function that you need to be aware of is scope. When a variable is created inside a function, as in the example above, that variable is said to have limited scope. By that we mean the variable only really exists, and therefore should only be referenced from, the function in which it was created. The code outside of the function does not know the cel exists. Try the following:

function calcTemp(fah){
	var cel = (fah -32) * 5/9;
	return cel;
}
calcTemp(61);
////////// this won't work as 'cel' is not in scope /////////////
console.info(cel);

Your console will throw an error as the Javascript outside the curlies of the calcTemp function has no idea what you are talking about when your reference cel as it is out of scope.

This demo shows this classic beginner's program in action. To view the code in the demo most browsers will allow you right-click and choose an option such as 'View Source'. You'll see our calcTemp function in the code but you'll also see lots of other stuff like document.getElementById . We'll come to what this does shortly, as it is key to using Javascript in a web browser and is do with changing the HTML on the fly or in technie terms 'Manipulating the DOM'.

One last comment on comments

In your Javascript you may wish to put aid-memoirs / little notes to help you recall why you did something. We call these comments and they can be added two ways in Javascript.

Single line comments are created by adding // at the beginning of the line of code.

Multi-line comments can be created by adding /* then */


// this is a single line comment

/*
This is
a multiline
comment
*/

More information on different ways to write functions in Javascript available here.

Leave a Reply

*