Functions as argument

Description

function names in Javascript are variables, so functions can be used as value.

We can pass a function as an argument.

Example


function callSomeFunction(someFunction, someArgument){
   return someFunction(someArgument);//  w  w w.  ja  va2  s. co  m
}
function add10(num){
   return num + 10;
}

var result1 = callSomeFunction(add10, 10);
console.log(result1);   //20

function addString(name){
   return "Hello, " + name;
}

var result2 = callSomeFunction(addString, "XML");
console.log(result2);   

This function accepts two arguments. The first argument should be a function, and the second argument should be a value to pass to that function.

The code above generates the following result.





















Home »
  Javascript »
    Javascript Introduction »




Script Element
Syntax
Data Type
Operator
Statement
Array
Primitive Wrapper Types
Function
Object-Oriented
Date
DOM
JSON
Regular Expressions