Lesson 8: Package your JavaScript Code with Functions

By Maria Antonietta Perna

You can already add quite a bit of JavaScript functionality to web pages, and that's great. However, what if you decide to implement the same kind of functionality on more than one page, or in different places on the same page?

This is where JavaScript functions come into play.

In this lesson, you will learn:

  • what functions are and how they are used in JavaScript;
  • how to retrieve information from functions;
  • how to give information to functions;
  • what variable scope is all about.

In the process you will also learn how to:

  • get today's date dynamically;
  • change the value of an HTML button element dynamically.

Functions: what they are and what they are for

In previous lessons you used JavaScript functions to perform some actions quickly and easily like generating random numbers, writing something on a web page, etc. In fact, JavaScript has a great many built-in functions like write(), alert(), getElementById(), random(), floor(), and several others. Wherever you spot a pair of round brackets there's likely a function in action.

JavaScript also gives you the option to craft your own functions.

A function is a way of packaging your JavaScript commands so you can easily reuse them every time you need the same piece of functionality implemented in your website.

This suggests that there are 2 distinct phases to a function:

  1. The phase where the function is declared (created);

  2. The phase where the function is called (used).

Let's go through each phase in turn.

Declare a function

The basic structure of a JavaScript function looks like this:

	
	  //keyword function followed by your
	
	  //chosen name for the function
	
	  //Don't forget the round brackets!
	
	  function functionName()
	
	  //the code block is inside curly braces
	
	  {
	
	  //code you want to run goes here
	
	  }
	
	  

Call a function

Once you put a block of code into a function, you can use it anywhere you need that functionality in your website. What you need to do is just call the function.

You do this by typing the function name followed by brackets and the function will do its job - just like you did with alert(). Here's how it's done:

	
	  //Type the function name (without the keyword function)
	
	  //Don't forget the round brackets!
	
	  functionName();
	
	  

That's all you need: whatever code you stuffed into your function gets executed at this point.

Let's see how this works in practice. Fire off your text editor: it's time to get coding!

Try out: declare your function

Prepare a simple HTML page like the one below. The program we're going to build has the following goals:

  • to get today's date dynamically when the user clicks a button;
  • to display today's date on the web page;
  • to change the value attribute of the button after it's clicked: to have the button still displaying Get Date after the date has been displayed looks a bit confusing to the user.
	
	  <!DOCTYPE html>
	  <html>
	  <head>
	  <title>Lesson 8: Declare a function</title>
	  </head>
	  <body>
	  <h1>Lesson 8: Declare a function</h1>
	
	  <div>
	
	    <h2>Today's date is:</h2>
	  
	    <span id="calendar"></span>
	  
	    <input type="button" id="myButton" value="Get Date" />
	
	
	  </div>
	  
	  <script type="text/javascript">
	
	  //Declare your function here
	
	  function showDate()
	
	  {
	
	  //the block of code starts here:
	
	  //First get all your vars ready
	
	  //This is how JavaScript retrieves today's date
	
	  var today = new Date();
	
	  //get hold of the calendar span element
	
	  //where today's date will be inserted
	
	  var myCalendar = document.getElementById("calendar");
	
	  //get hold of the button:you need this when it comes
	
	  //to change its value attribute
	
	  var myButton = document.getElementById("myButton");
	
	  //insert the date in the span element.
	
	  //toDateString() changes the date just retrieved
	
	  //into a user-friendly format for display
	
	  myCalendar.innerHTML = today.toDateString();
	
	  //change the value attribute of the button
	
	  //to say something more appropriate once the date is displayed
	
	  myButton.value = "Well done!";
	
	  }
	
	  </script>
		
	  </body>
	  </html>
	
	  

Try out: call your function

If you review your program's goals as set out at the beginning, you'll see that all the action takes place after the user clicks the button on the page. This tells us that we need to handle the button's onclick event.

If you go back to lesson 3 for a moment, you remember that one way in which this can easily be done is to put some JavaScript code as the value of the HTML element onclick attribute.

Just add an onclick attribute to the button element and plug your showDate() function right in there, like so:

	
	  <input type="button" id="myButton" value="Get Date" onclick="showDate();" />
	
	  

Save your work and run the page in the browser. Click the button and you should see today's date displayed on the page and the button value attribute giving you an appropriate message.

Questions, questions, questions

I know, there's some new stuff in the code samples above. You might be wondering: 1) what's this new Date() business? And 2) What does toDateString() do to the date? Let's tackle each question in turn.

  1. What's new Date() all about?

    The new keyword creates a new instance of a JavaScript object, in this case a Date object based on the user's computer clock. Objects are the topic of the next lesson, and the Date object is the topic of lesson 11. Therefore, I keep things really short at this point.

    The important thing you need to know now is that once you've created an instance of the Date object, you've got all sorts of useful functions (called the object's methods) at your fingertips to manipulate date and time.

  2. Why did I use toDateString() with the date?

    Following on from the previous point, toDateString() is only one of the numerous methods you can use with the Date object. The JavaScript interpreter reads it as follows:

    "Hey browser, take the date you've been attached to and make it a bit more human-friendly!"

    This is what I mean. Type the following inside enclosing <script> tags of an HTML page: var myDate = new Date(); document.write(myDate);

    Save the page and run it in the browser: your date should be displayed in a format like the one below (obviously I expect the date to be different):

    Sun Nov 06 2011 14:45:30 GMT+0000 (GMT Standard Time)

    Ugly! Luckily, the Date object has its own beauty remedy. Rewrite the previous code snippet as follows: var myDate = new Date(); document.write(myDate.toDateString());

    And here's what the date above looks like after its beauty treatment with toDateString():

    Sun Nov 06 2011.

    Much better, less scary, and far more readable for us humans.

Feed information to and retrieve information from a function

Functions manipulate data: the alert() function has messages to display as its data, the write() function has text to write on the web page as its data, etc.

You can also feed data to a function for manipulation. The way you do this is through arguments (or parameters). An argument is placed inside the function's brackets when the function is declared. You can place one or more arguments separated by commas( , ) inside a function.

Here's what the basic structure looks like:

	
	  function functionName(arg1, arg2, arg3)
	
	  {
	
	  //body of the function goes here
	
	  }
	
	  

The function argument is like a placeholder for the value that gets fed when the function is called. This will appear clearer in the example below.

Finally, one useful thing functions can do with data, once it's been manipulated, is to return it.

For example, take the floor(number) function that you already know from the previous lesson. This function takes in a number argument and returns an integer number.

If your script does something with the returned value then it needs to assign the function to a variable when calling the function.

Let's put this knowledge into practice right away. Create a function and then call it to use its return value in your document.

Declare a function with a parameter

Prepare a simple HTML page and type the following JavaScript code within <script> ... </script> tags:

	
	  <!DOCTYPE html>
	  <html>
	  <head>
	  <title>Lesson 8: Function Arguments and Return Values</title>
	  </head>
	  <body>
	  <h1>Lesson 8: Function Arguments and Return Values</h1>
	  
	  <script type="text/javascript">
	
	  //declare a function with two arguments of type number
	
	  function addNumbers(num1, num2)
	
	  {
	
	  //this is a simple function:
	
	  // just return the sum of the two number arguments
	
	  return num1 + num2;
	
	  //your function ends here
	
	  }
	
	  </script>
		
	  </body>
	  </html>
	
	  

Call your function and use its return value

Continue on from the previous code. Outside your function, just after the } closing curly brace, type the following:

	
	  //Call your function: create a var
	
	  //and assign the value returned by your function to it
	
	  //Also, give a value to the number arguments
	
	  //by typing 2 comma-separated numbers within brackets
	
	  var total = addNumbers(3, 5);
	
	  //Display the returned data on the page
	
	  document.write(total);
	
	  

Save your work and run the page in the browser. If all goes well, the sum of the numbers you inserted as arguments of your addNumbers() function should be displayed on the web page.

Function arguments are not limited to a specific data type. You can also use strings and booleans, and even other functions. However, we don't want to be too involved at this stage.

Variables inside and outside functions: scope

A variable can have local or global scope on the basis of whether it's declared inside or outside a function block.. But, what does this mean exactly?

Simply put, a variable having local scope means that it's visible, or accessible, only within the function in which it lives. No other portion of your code can see a local variable.

On the other hand, a variable having global scope means that it's accessible, that is, it can be used, anywhere in your script.. Let's see this in practice. Get your text editor ready and type the following snippet between opening and closing <script> tags in an HTML page:

	
	  //create 2 global variables
	
	  var message = "outside global message";
	
	  var otherGlobalVariable = "other global variable";
		
	  //create a function with a local variable
	
	  //having the same name as the first global variable
	
	  function getMessage()
	
	  {
	
	  var message = "inside local variable";
	
	  //the function alerts the message variable
	
	  alert(message);
	
	  //and it also alerts the second global variable
	
	  alert(otherGlobalVariable);
	
	  //the function ends here
	
	  }
	
	  //call the function
	
	  getMessage();
		
	  //alert the message variable
	
	  //(which one will it be, local or global?)
	
	  alert(message);
	
	  

Save your work and preview the page in your browser. As you can see, the alert() function outside the variable doesn't have access to the message variable inside the function. On the other hand, the function can have access both to its local variable and to any variable in the global space.

This might seem a bit confusing at first, but it's all a matter of practicing your coding skills as often as you can. The important thing to remember is that, if at times the variables seem not to have the values you expect, it might be a scope-related bug.

Summary

That's all for this lesson. You can now package your JavaScript code into reusable and manageable functions, input and output data via a function, use the Date object to retrieve and display the current date, change the value of an HTML button element on-the-fly, and distinguish between local and global variables. You've accomplished a great deal, congratulations!

Take a break and get ready for the next big topic, a core feature of contemporary programming languages, objects.


Related topics in the RepliesViews
No related topics yet

+ Post a new topic


<< Lesson 7: Leave Boring Repetitive Stuff to JavaScript with Loops

Lesson 9: A Gentle Introduction to Objects >>