A function is a block of code that is called using its function name.


Functions are declared using the keyword function, followed by the identifier aka token / function name and zero or more parameters to pass into the function within parentheses.



function myFunction(parameters){




To use the function it is called by using the function name .e.g myFunction(parameters) ;


This example shows three functions. The first simply calls a function with no parameters. The second function is called with a single parameter (bike) that is passed in to the function, which also uses the global topSpeed variable. Finally the third function also passes in the topSpeed global variable but also returns a value that is used in the last statement:

	<script type="text/javascript">

		var topSpeed = 202 ; //globally scoped

		function ifOnly(){
			document.write("If only I could afford one of these!<br>");


		function myFunction(bike){
			document.write("My "+ bike + " has a top speed of " + topSpeed + "mph!<br>");
		myFunction("Ducati Panigale R");

		function firstGear(aParameter){
			return (aParameter / 3).toFixed(2) ;

		document.write("Spanking out " + firstGear(topSpeed) + "mph in just the 1st gear!");


Save & refresh browser:

If only I could afford one of these!
My Ducati Panigale R has a top speed of 202mph!
Spanking out 67.33mph in just the 1st gear!

Leave a Reply