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:

Air Resistance and Terminal Velocity

View this item in the topic:


and many more articles in the subject:

Subject of the Week


Physics is the science of the very small and the very large. Learn about Isaac Newton, who gave us the laws of motion and optics, and Albert Einstein, who explained the relativity of all things, as well as catch up on all the latest news about Physics, on

Gravity lens

Great Scientists

Maurice Wilkins

1916 - 2004

Maurice Wilkins, 1916 - 2004, molecular biologist, was 'the third man of the double helix', as his biography title declares. Born in New Zealand, but did most of his professional work in England, Wilkins shared the Nobel Prize with Crick and Watson.

Maurice Wilkins