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, ....) {

statements

}

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() {
document.write('<ol>')

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

}

document.write('</ol>')
}

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>

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

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>

<script>
function change_styles() {
    var element_to_change = document.getElementById("stylechange");
    element_to_change.style.fontSize = "20px";           
    element_to_change.style.color = "#000"; 
    element_to_change.style.margin = "20px 100px"; 
}
</script>
<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 © Andrew Bone. 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:

Mechanics

and many more articles in the subject:

Subject of the Week

Physics

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 ScienceLibrary.info.

Gravity lens

Great Scientists

Theodor Schwann

1810 - 1882

Theodor Schwann was a German scientist who had a profound impact on biology by breaking with entrenched concepts prevalent in the mid 19th century.

Theodor Schwann
SaraOrdine

Quote of the day...

All models are wrong, but some are useful.

ZumGuy Internet Promotions

Yoga in Mendrisio