Array of functions in JavaScript

In JavaScript, a function can work like a normal variable. Therefore, it can be an item of an array. In the example code below, function sum and subtract are the items of the ar array. Accessing function items of the array is almost the same as accessing normal items. The difference is that the normal item is accessed without parentheses and the function item is accessed with parentheses.

<title>Call function</title>
<script type="text/javascript">

var sum=function(val1,val2){ //define sum function
var subtract=function(val1,val2){ //define subtract function

var ar=new Array(sum,subtract); //create an array of functions--sum and subtract
var res1=ar[0](12,34); //call the sum function
var res2=ar[1](12,34); //call the subtract function
alert("Sum reesult:"+res1+"\nSubtraction result:"+res2);




Posted by: Dara | post date: 03-25-2013 | Subject: JavaScript

This website intents to provide free and high quality tutorials, examples, exercises and solutions, questions and answers of programming and scripting languages:
C, C++, C#, Java, VB.NET, Python, VBA,PHP & Mysql, SQL, JSP, ASP.NET,HTML, CSS, JQuery, JavaScript and other applications such as MS Excel, MS Access, and MS Word. However, we don't guarantee all things of the web are accurate. If you find any error, please report it then we will take actions to correct it as soon as possible.