Oct 08, 2012
Table of contents:
Functions are one of the fundamental aspects of any programming language and are the building blocks to creating powerful applications. A function is basically a saved set of instructions that you want to use many times throughout an application.
When you are writing code for an application, you will find that you will begin repeating yourself in certain situations. When you have repeated a certain set of instructions, you need to abstract those instructions to a single point of contact and then reference that source.
For example, say you wanted to greet a user of your website. You might want to print "Hello " + username
to the screen. Greeting a user might be something that you want to appear in separate places across your website so you copy and paste that code to each of these place. But what happens when you want to change “Hello” with “Good morning”?. Well you would have to find each time that chunk of code is written throughout your system and manually change it.
This is a simple example, and it doesn’t really do justice to the power of functions, but I hope you see my point. A good Developer should always follow the Don’t Repeat Yourself (DRY) principle.
Anyway, with that introduction, here is how to create and use functions in Javascript. I’m introducing functions in Javascript, but the theory applies to just about every programming language.
This tutorial follows on from the previous tutorial, Basics of Javascript.
Functions can seem daunting if you are used to just writing long lists of code that just flows down your page, but they are really very easy to understand.
A function in Javascript begins with the key word function
:
function
Next we need to give our function a name so that we can reference it. You can use numbers, letters and some special characters in your function names. However it’s usually best to keep it descriptive to what the function actually does.
function whatsGood
Notice how I wrote the name of the function with a lowercase first letter of the first word, but a upper case first letter of the second word. This is an example of CamelCase, a common way of writing function or variables names in programming languages.
Next we need our function to receive inputs. Think of a function as a machine in a factory. The machine takes the raw materials and outputs the returned result.
To input data into a function we use a list of arguments wrapped in parenthesis.
function whatsGood (name)
In the example above, we are simply giving the function a user’s name.
Next we need a way of signalling the start and end of the functions code. To do this we use curly brackets.
function whatsGood(name) {
// Function code
}
And that is the basic anatomy of a function.
So now that you know how to create a function, let’s create a simple function to greet a new visitor to a webpage.
// Create the function
function whatsGood() {
alert("What's good homie?");
}
// Run the function
whatsGood();
Now that you understand the anatomy of a Javascript function, you should fully understand the code above. Notice how I’m not giving the function any inputs. Even when you don’t want to supply your function with arguments, you still need to use the parenthesis as this is how Javascript knows it’s a function.
Next you will see the line that says:
whatsGood();
This is how we tell Javascript that we want to run our function.
Functions are little stored bits of code that we can call when we need them. In order to run the code, first you must tell Javascript to run it. To run a function, simply write the function name with parenthesis and a semicolon. If you wanted to supply arguments to the function, this is where you would enter them.
So if you save that chunk of code into a webpage and open it in the browser, you should see the alert box we just created.
Now whenever you want to run that greeting, you can just run the function.
whatsGood();
So what about if we wanted to change the greeting to something else? Well all we would have to do would be to change the single instance of the greeting in the function.
function whatsGood() {
alert("What's good my good sir?");
}
Now everywhere that we have referenced that function will all be updated together.
An important aspect of functions is the ability to accept, process and return data. To input data we supply the function with “arguments”.
So to supply our function with an argument, just add it into the parenthesis.
function whatsGood(name) {
alert("What's good " + name);
}
Next modify the rest of your code to accept an input from your user.
var name = prompt("What's your name?");
Here we are declaring a new variable of name
with the keyword var
and then we use the global prompt
function to pop an input box to the screen which allows our user to enter their name.
So the full code would be:
// Function
function whatsGood(name) {
alert("What's good " + name);
}
// Get name
var name = prompt("What's your name?");
// Run function
whatsGood(name);
Now if you run the code in a web browser you should be able to enter your name into the script through the prompt box and have an alert box greet you.
To use multiple arguments in a function, you simply list them within the parenthesis and separate them with commas.
function calculate(x, y, z) {
var sum = x + y + z;
alert("x + y + z is equal to " + sum);
}
Arguments are how we input into a function, but how to get the output? Well as you have seen in the example so far, we could just use something like an alert to display a message, but this isn’t all the useful.
Functions have an inbuilt way of handling output. To output from a function, simply use the return
key word.
function addNumbers(x, y) {
return x + y;
}
As you can see in the example above, we input x and y, and then we return the sum of x + y.
So to use this function we could write:
var x = 20;
var y = 33;
var total = addNumbers(x, y);
Scope is an important concept to understand in programming languages.
Scope basically means, the context for which something is used. So you could say globally “trees are green” but within this very specific greenhouse, “trees are purple”. The fact that trees are purple within the greenhouse does not change the fact that trees are green globally.
So say you had the following variable:
var trees = "green";
Whenever you wanted to see what the colours of trees were, you could simply reference the variable name trees
.
But what if you wanted to make a special greenhouse?
function greenhouse() {
var trees = "purple";
return trees;
}
Now if you ran the greenhouse function, you would be returned purple, but this would not affect the global variable that has already been set.
For example:
var trees = "green";
console.log(trees); // returns "green"
// Create the greenhouse
function greenhouse() {
var trees = "purple";
return trees;
}
// Run the greenhouse
console.log(greenhouse()); // Returns "purple"
console.log(trees); // returns "green"
Scope is an important concept to understand. Basically, all you need to remember is that things are dependant on the scope that you’ve set them.
Scope also cascades down. So if you set something globally, you can still access it within a function.
var today = "Monday";
function alarm() {
alert("Today is " + today);
}
But what do you think will happen if we write something like this?
var today = "Monday";
function alarm() {
var today = "Sunday";
alert("Today is " + today);
}
Well, if you run this function, the alert box would say “Today is Sunday”. This is known as shadowing, where you create a variable at a scope that is already in use at another scope.
The easiest way to avoid this problem is to just not use the same variable names. This prevents any silly bugs or confusion.
And there you have it, that is the basics of Javascript functions. There is still more to cover with Javascript functions, but hopefully you understand the purpose of a function, why you should use them and how to use them in their basic form.
Next time we will be looking at Javascript Objects.