1. Technology

JavaScript By Example

15. Functions

By

Functions provide one of the simplest ways of breaking up our code into modules and making it easier to understand.

There are three different ways to define a function in JavaScript but one of the three has so many advantages over the other two that you may as well use it to define all your functions. This particular way of defining functions usually assigns the function to a variable. We don't need to define that variable first when we are going to use it to hold a function rather than a value though.

A function may or may not define arguments that it expects to have passed to it and it may or may not return a value to the code that called it. We call a function by specifying the name of the variable that the function is assigned to followed directly by (). If we need to pass parameters to a function we place those within the () and if arguments are defined the arguments will be assigned the values of the corresponding parameters.

Here we take our ternary operator example and split the code into two functions which we call getColour and displayMessage. The first of these doesn't have any arguments but returns a value. The second of these does have an argument but doesn't return a value (functions are allowed to do both at the same time, just we don't need to with either of these functions).

HTML


<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"
"http://www.w3.org/TR/html4/strict.dtd">
<head>
<title>Example 15</title>
</head>
<body>
<p id="ex"></p>
<script type="text/javascript" src="example15.js"></script>
</body>
</html>

JavaScript


var col;
getColour = function() {
return window.location.search.substring(1);
};
displayMessage = function(colour) {

var favcol;
favcol = ('green' === colour) ? 'is green.' : 'is not green.';
document.getElementById('ex').innerHTML = colour + favcol;
};
col = getColour();
displayMessage(col);

  1. About.com
  2. Technology
  3. JavaScript
  4. Javascript Tutorials
  5. JavaScript By Example
  6. JavaScript By Example - Functions

©2014 About.com. All rights reserved.