Science Library - free educational site

Functions (JS)

There are built-in functions, which are common to any JavaScript programme, and do not have to be defined. An example is:

document.write('This is using the built-in function write')

Functions can also be created for a specific script. Provided the function name is not a reserved name (i.e. JS already knows what it means, like write), a function may be created and used at will. This helps to condense and organise scripts, especially with regularly used actions, and leads to much more versatile and powerful programmes.

The syntax for defining a function is:

function function_name(parameter1, parameter2, ....) {



Function names in JS are case sensitive, can be any length, and contain any combination of letters, numbers, dollar signs or underscores. The only restriction is that function names must not start with a number. There is a convention (bumpyCaps), in which the first letter of each word is capitalised, except for the first word: e.g. myListOfFavouriteFruit(). It is not mandatory, but has become standard, being the most readable of formats.

One or more parameters may be called, but are optional. The parentheses must be used even if no parameters are used. Curley braces {} open and close function statements.

calcPrice(400, 0.05)

function calcPrice(listed_price, discount){

document.write(listed_price - (listed_price*discount));


Example of an arguments array

listFruit('apple', 'banana', 'grapefruit', 'pineapple')

function listFruit(f1, f2, f3, f4) {
document.write('<ol><li>' + f1 + '</li>')
document.write('<li>' + f2 + '</li>')
document.write('<li>' + f3 + '</li>')
document.write('<li>' + f4 + '</li></ol>')

The output of the above script is:

To avoid needing to know exactly how many arguments there are, a loop may be used with the length property of the listFruit.arguments array:

listFruit('apple', 'banana', 'grapefruit', 'pineapple', 'orange', 'grape')
function listFruit() {

for (j=0 ; j < listFruit.arguments.length; ++j) 
document.write('<li>' + listFruit.arguments[j] + '</li>')



The output of the above script is:

Example of an inline function call.

Wake the duck up by clicking on him.

<img id="Duck" onclick="changeImage()" src="duck_asleep.png" width="80" height="80">

<p>Wake the duck up by clicking on him.</p>

  function changeImage() {
     var image = document.getElementById('Duck');
     if (image.src.match("awake")) {
        image.src = "duck_asleep.png";
     } else {
        image.src = "duck_awake.png";

Changing Styles with JS

Change this style.

Not all styling can be changed in this way. For example, margin works, but margin-left does not. border works but border-radius does not.

<p id="stylechange">JavaScript can change the style of an HTML element.</p>

function change_styles() {
    var element_to_change = document.getElementById("stylechange"); = "20px";       = "#000"; = "20px 100px"; 
<button type="button" onclick="change_styles()">Change Styles</button>

The above code displays the following:

JavaScript can change the style of an HTML element.

Returning a Value

The above examples are of functions displaying information. However, functions are mainly used for performing calculations or other data manipulations, then returning a result. As an example, let us use JavaScript's built in method charAt and substr to convert any string to a name format, with capital first letter and lowercase remaining letters in a word.

document.write(nameformat("PETER", "arChiDuke", "smiggins", 
"direcTor", "OPERationS"))

function nameformat() {
 var string = ""
 //initialize the string variable to empty string

 j = nameformat.arguments.length

 for (i = 0 ; i < j-3 ; ++i) {
   string += nameformat.arguments[i].charAt(0).toUpperCase() +
	nameformat.arguments[i].substr(1).toLowerCase() + " "}

   string += nameformat.arguments[j-3].charAt(0).toUpperCase() +
	nameformat.arguments[j-3].substr(1).toLowerCase() + ": " 

   string += nameformat.arguments[j-2].charAt(0).toUpperCase() +
	nameformat.arguments[j-2].substr(1).toLowerCase() + " of " 
   string += nameformat.arguments[j-1].charAt(0).toUpperCase() +
	nameformat.arguments[j-1].substr(1).toLowerCase() + "." 

	return string.substr(0, string.length)

This code returns the content of string: Peter Archiduke Smiggins: Director of Operations.

In the final statement, the second parameter string.length specifies how many characters to return, starting the first character as '0'. This is not strictly necessary, since the method substr assumes you want the rest of the string and will return it all anyway, unless instructed otherwise.

For example, a long list of members of a club can be printed out, with a comma and space between the names (this is the case of data from a csv file). To remove the final comma and space after the last name, the string length is reduced by 2 characters by specifying people.length-2 as the second parameter in the substr method of the return statement:

document.write(nameformat("PETER", "charlie", "rOGer"))

function nameformat() {
	var people = ""
	//initialize the people variable to empty string
	j = nameformat.arguments.length

	for (i = 0 ; i < j ; ++i) {
	people += nameformat.arguments[i].charAt(0).toUpperCase() +
		nameformat.arguments[i].substr(1).toLowerCase() + ", "
	return people.substr(0, people.length-2)

This code returns: Peter, Charlie, Roger

Returning an Array

Instead of returning all the names as a string, the information can be returned as an array.

names = nameformat("PETER", "CharLIE", "rOGer", "philamena", "HeRoNyMoUs");

for (i = 0; i < names.length ; ++i)
   document.write(i+1+". " + names[i] + ";
") function nameformat() { var people = new Array() j = nameformat.arguments.length for (i = 0 ; i < j ; ++i) { people[i] = nameformat.arguments[i].charAt(0).toUpperCase() + nameformat.arguments[i].substr(1).toLowerCase() } return people }

This script returns:

Content © Renewable.Media. All rights reserved. Created : June 3, 2014 Last updated :March 11, 2016

Latest Item on Science Library:

The most recent article is:


View this item in the topic:

Vectors and Trigonometry

and many more articles in the subject:

Subject of the Week


Science resources on Games, puzzles, enigmas, internet resources, science fiction and fact, the weird and the wonderful things about the natural world. Have fun while learning Science with


Great Scientists

Pierre-Simon Laplace

1749 - 1827

Pierre-Simon de Laplace was a French aristocrat who narrowly escaped the guillotine during the French Revolution. He was the mathematics tutor then friend of Napoleon Bonaparte at the École Militaire in Paris, and briefly became his Minister of the Interior in 1800.

Pierre-Simon de Laplace
Vitruvian Boy

Quote of the day...

The factory of the future will have only two employees: a man and a dog. The man will feed the dog. The dog will prevent the man from touching the machines.

Renewable.Media Internet Promotions