Javascript Function: Defining, Calling and Using Functions in Javascript

A Basic Function
A Function With Parameters
Calling a Function Using Onclick
Calling a Function When the Page is Loaded
Anonymous Functions and Function Pointers in Javascript


A Basic Function

You can create a function in javascript like this:


function something() {
	
}


A Function With Parameters

Of course, javascript functions can also accept and return parameters.

By way of example, here’s a function that accepts three strings (x, y and z) and returns those strings joined together with some space.

We’ll use the handy built-in alert() function to display the results.


function example(x, y, z) {
	var text = x + ' ' + y + ' ' + z;
	
	return text;
}

alert(example('hello', 'to', 'you'));


Calling a Function Using Onclick

Let’s take a look at an example of a function that pops up an alert box when you click an HTML form button. To call the function, we specify it in the onclick attribute of the button.


<html>
<head>

<script language="javascript">

function shout() {
	alert('Hello');
}

</script>
</head>

<body>

<input type="button" onclick="shout()" value="Say Hello" />

</body>
</html>


Calling a Function When the Page is Loaded

Often you want to call a javascript function when the page loads. For instance, you might have written a whole javascript application to generate your page content and you want the application to start when the page loads.

You could just call your function directly, so that it runs as soon as the browser parses it. However, other elements of your page will typically not be ready by then, so you can end up with unexpected results.

window.onload is the answer.


<html>
<head>

<script language="javascript">

function shout() {
	alert('Hello');
}

window.onload=shout;

</script>
</head>

<body>

</body>
</html>


Anonymous Functions and Function Pointers in Javascript

Often in javascript you want to supply a function as an argument to another function. This enables us to create some very powerful constructs in javascript. While you can simply define the function and pass in the function name, you can also define the function right where you pass it into the other function.

Here are examples of both.


// This function just runs any function that's
// passed to it.
function runner(run) {
	run();
}

// This function pops up an alert.
function hello() {
	alert('hello');
}

// Call hello() by passing it to runner().
runner(hello);

// Define an anonymous function while 
// simultaneously passing it to runner()

runner(function() {
	alert('goodbye');
});


All pages on this site are copyright © 2013 John W. Purcell

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

Posted in Javascript | Tagged , , |