Use function as variable in JavaScript

Description

The following code shows how to use function as variable.

Example


<!DOCTYPE html>
<html>
<head>
<script type="text/javascript">
function callFunction(aFunction, anArgument){
return aFunction(anArgument);<!--from w w  w .  j a v a  2  s .  com-->
}

function add10(num){
return num + 10;
}
var result1 = callFunction(add10, 10);

document.writeln(result1); //20

function getGreeting(name){
return "Hello, " + name;
}
var result2 = callFunction(getGreeting, "JavaScript");
document.writeln(result2); //"Hello, JavaScript"

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

Click to view the demo

The code above generates the following result.

Use function as variable in JavaScript