Functions in JavaScript

SEARCH THIS SITE

Custom Search



A function in javascript is a set of statements that performs a specific task. Functions are used when the same task (calculations for example) is performed with different parameters..

A simple Function in Javascript

In the javascript example program 1 below, the statement var w = myFirstFunction(a,b,c); invokes a function called myFirstFunction(a,b,c) and the result of the computation is stored in the variable w.
The statement
function myFirstFunction(x,y,z){
return y^2 - 4*x*z;
}

defines the function whose name is myFirstFunction(x,y,z) with parameters x, y and z. When the function is invoked, the values in the arguments a, b and c are stored in x, y and z respectively. Then the function evaluates the arithmetic expression y^2 - 4*x*z then returns to the point where it has been invoked. In this case the result is stored in the variable w.
Run Javascript Example Program 1 and check that the answer is - 39.

Javascript Example Program 1

<!DOCTYPE html>
<html>
<body>
<script>
var a = 2, b = 3 , c = 6;
var w = myFirstFunction(a,b,c);
alert(w);
function myFirstFunction(x,y,z){
return y*y - 4*x*z;
}

</script>
</body>
</html>

Invoke a Function from Inside Another Function

In the javascript example program 2 below, two functions firstFunction and secondFunction have been defined. Function secondFunction is invoked twice from within function firstFunction.
Run the sample program below and check that the answer displayed is 106. ( (2 + 3)(2 + 3) + (-2 - 7)(-2 - 7) = 106 )

Javascript Example Program 2

<!DOCTYPE html>
<html>
<body>
<script>
var a = 2, b = 3, c = -2, d = -7;
var t = firstFunction(a,b,c,d);
alert(t);
function firstFunction(x,y,z,w){
return secondFunction(x+y) + secondFunction(z+w);
}

function secondFunction(w){
return w*w;
}

</script>
</body>
</html >


Books and References

1 - A Smarter Way to Learn JavaScript: The new approach that uses technology to cut your effort in half - Mark Myers
2 - JavaScript and JQuery: Interactive Front-End Web Development 1st Edition - Jon Duckett - ISBN-13: 978-1118531648
3 - A Smarter Way to Learn HTML & CSS: Learn it faster. Remember it longer. (Volume 2) - Mark Myers
4 - http://www.w3schools.com/js/default.asp - JavaScript Tutorial