Core JavaScript

Anonymous Functions

A function defines a block of code that can be executed from almost anywhere with a function call. Functions can take in a set of values, which are called parameters, when they are called. Additionally, they can return a value to the location where they were called.

The program below contains two functions which are each called once. The first function is F(). It takes in two values labeled X and Y and returns the value of their product times 3 or 3XY. It is called with the values 2 and 5 passed in. The second function has no name and is what is called an anonymous function; it returns the sum of its 2 parameters. Although the function is anonymous, the variable G is immediately set to this function so that it can be called via that variable. Finally, the anonymous function is called via G with the values 10 and 4 passed in.

AnonymousFn.html

<!DOCTYPE html>
<html>
<head>
    <title>XoaX.net's Javascript</title>
</head>
<body>
    <script type="text/javascript" src="AnonymousFn.js"></script>
</body>
</html>

AnonymousFn.js

function F(X,Y) {
	return 3*X*Y;
}

document.writeln("F(2, 5) = " + F(2, 5) + "<br />");

var G = function(X, Y) {
	return X+Y;
}
document.writeln("Anonymous Function = " + G(10, 4) + "<br />");
 

Output

 
 

© 2007–2024 XoaX.net LLC. All rights reserved.