Class 5 – Javascript Functions

Whereas variables store a piece of data in memory, functions store a series of commands in memory to be run at a later time.  Think of a function as a block of code that performs a  specific task.

Defining a function

For example, let’s say we have a function that does one thing – it pops up a message with the word, “hello.”

function sayHello() {
  alert("hello");
}

Let’s take this function line-by-line:

function sayHello() {

This line of code declares that the following block of code will be a function by using the keyword “function” (similar to how a variable is declared with the “var” keyword).  Then it defines the name of the function as “sayHello”.

  alert("hello");

This line of code calls the browser’s built-in “alert” function, which will automagically pop up an alert box with the word “hello” in it when it is run.

}

This last line of code just has a closing bracket, “}”.  This tells the browser, which is reading this code, that this is the end of the function.  Everything between the opening bracket, “{“, and the closing bracket, “}”, is a block of code (i.e., a set of commands) that is stored in memory and is only executed when we call the function named “sayHello.”

Calling the function

It’s all well and good to define a function, as we have done above.  But the browser does not actually perform the actions defined in the function.  It simply stores them in memory for use later.

In order to actually run the commands stored in the function, we have to “call” the function.  This usually happens somewhere else in the code, outside of the function block.

To call the function we defined above, we would use the following code:

sayHello();

This would run the commands in the function, which would result in the word “hello” appearing in a pop-up alert box.

Passing parameters to functions

Let’s say we wanted to make the message that pops up in the alert box customizable.  For example, we want the message to have someone’s name in it, such as “hello, Martha” or “hello, Juan”, or “hello, Fausta.”

We want to be able to use this same function to say hello to all these people.  How do we do it?

We could just write a separate function for each person, like this:

function sayHelloToMartha() {
  alert("hello, Martha");
}
function sayHelloToJuan() {
  alert("hello, Juan");
}
function sayHelloToFausta() {
  alert("hello, Fausta");
}

and whenever we want to pop up a message for Martha we call her function in our code:

sayHelloToMartha();

and when we want to pop up a message for Juan, we call his function:

sayHelloToJuan();

…and so on.

However, this can become very inefficient if there are lots of variations on the same basic function.  There is an easier way using parameters.

We can design a version of our original function that takes one “parameter” or input.  When we call the function, we tell the function the name of the person to whom to say hello, and it outputs a message customized to that person.

Here is what our function will look like:

function sayHello(person) {
  alert("hello," + person);
}

This single function can say hello to just about anybody we tell it to.  Let’s take it line by line:

function sayHello(person) {

This declares that we are defining a function named “sayHello” and that it accepts one parameter, which we call “person”.

Note: Anytime you see words in between the parentheses of a function definition, they indicate parameters that the function accepts as input when it is called.

  alert("hello," + person);

Here we are again using the browser’s built-in “alert” function in order to pop up a message in an alert box.  However, the message we are popping up is no longer just a simple “hello”.  The message we are popping up (i.e. the stuff between the parentheses of the alert function call) is now:

"hello," + person

This takes the word “hello,” and glues it to the name we will use as a parameter when we called the function. The word “hello”, in this case, is a string literal, which we saw in the discussion on variables.  You can tell this because it is text surrounded by quotes.  The term “person” is a variable name, which you can tell because it is text not surrounded by quotes.

So the word “hello” is concatenated with, or glued onto, whatever word is stored in the variable named “person”.

If we call the function and pass it the word “Martha” as a parameter, the function takes the word, “Martha”, stores it in a variable named “person”, and concatenates this variable with the word “hello”.  Then it pops up an alert message with the combined message, which contains the words, “hello, Martha”.

Calling the function with the word “Martha” as a parameter looks like this:

sayHello("Martha");

If we pass it the word “Simon”, it will say “hello, Simon”:

sayHello("Simon");

If we pass it the word, “Susan”, it will pop up “hello, Susan”:

sayHello("Susan");

etc.

More about parameters and variable scope

Functions are not limited to just accepting one parameter as input.  Functions can take as many parameters as you want them to when you design them.

function doSomething(parameter1, parameter2) { ... }

In any function definition, the stuff between the parentheses is a comma-delimited list of parameters.  Parameters are values that the function will accept when it is called.  They are variables that automatically hold the values that were passed to the function when it was called.

When we call a function, we supply it with a list of arguments.  These can be variables or literals. In the following example function call we’re using two literals, but these arguments could just as easily be variables: the two are interchangeable as far as the code is concerned, and it really depends on what you’re trying to achieve which one you use.

doSomething("hello", 100);

When we call the function this way, the argument “hello” is stored in the function’s first parameter variable, “parameter1″.  The second argument, 100, is stored in the function’s second parameter variable, “parameter2″.

Within the function block (anywhere between the brackets “{” and “}”) , the variable “parameter1″ holds the value “hello”, and “parameter2″ holds the value 100.  These parameter variables only exist within that function, and are said to have a local scope to that function.  Referring to the variable named “parameter1″ outside of the function is meaningless.

So the term “arguments” refers to values that are supplied to a function when that function is called somewhere in your code.  Parameters are the flip-side of arguments – the term “parameters” refers to the values that the function accepts and stores in variables when it is called.  Whatever you supply as arguments to a function are then stored temporarily in that function’s parameters.

Return values

Some functions have return values.  This means that when the function is called, it takes some kind of input, performs a specific function on that input, and then returns the results of that process to the code that called it.

This is probably best illustrated with an example:

function addOne(someNumber) {
  var newNumber = someNumber + 1;
  return newNumber;
}

This function defines a block of code that takes some number and adds one to it.  Then it returns the new number.

So if we call this number, and give it the number 10 as an argument, we will get the number 11 back.  This is how we’d call the function and supply it with the argument, 10.

addOne(10);

But in order to see that this works, we would have to do something we the number we get back, like, for example, popping it up in an alert message.  So let’s first store the returned value in a variable, and then pop up the contents of that variable in an alert pop-up.

var result = addOne(10);
alert(result);

So we can see that the return value of the function was 11.  If we supplied the function with the parameter 3, the return value would be 4, and so on.

Function names

Like variable names, function names must not have any spaces or special characters in them, although they can use the underscore (“_”) character.  They also generally use the CamelCase convention.

Related posts:

  1. Class 5 – Javascript Variables
  2. Class 5 – How to place Javascript code on a page
  3. Class 5 – Basic Javascript Examples
  4. Class 5 – What is the Javascript Document Object Model?

Tags:

Leave a Reply