In a recent question, I received suggestions to talk on, amongst other things, the aspect of JavaScript where functions are \'first class\' objects. What does the \'first c
Definition on the Mozilla site is concise and clear. According to them,
In JavaScript, functions are first-class objects, because they can have properties and methods just like any other object. What distinguishes them from other objects is that functions can be called. In brief, they are Function objects.
And
a function is a "subprogram" that can be called by code external (or internal in the case of recursion) to the function. Like the program itself, a function is composed of a sequence of statements called the function body. Values can be passed to a function, and the function will return a value.
The notion of "first-class functions" in a programming language was introduced by British computer scientist Christopher Strachey in the 1960s. The most famous formulation of this principle is probably in Structure and Interpretation of Computer Programs by Gerald Jay Sussman and Harry Abelson:
Basically, it means that you can do with functions everything that you can do with all other elements in the programming language. So, in the case of JavaScript, it means that everything you can do with an Integer, a String, an Array or any other kind of Object, you can also do with functions.
Simple in JavaScript, functions are first-class objects that is, functions are of the type Object and they can be used in a first-class manner like any other object (String, Array, Number, etc.) since they are in fact objects themselves. They can be “stored in variables, passed as arguments to functions, created within functions, and returned from functions
In javascript functions are first class objects because it can do a lot more than what objects can do.
Function instanceof Object //returns true
Like an object a function can have properties and can have a link back to it’s constructor function.
var o = {}; // empty object 'o'
o.a = 1 ;
o.b = 2 ;
console.log(o.a); // 1
console.log(o.b); // 2
function foo(){};
foo.a = 3 ;
foo.b = 4 ;
console.log(foo.a); // logs 3
console.log(foo.b); // logs 4
var foo = function(){};
console.log(foo); // function(){}
function callback (foo){
foo();
}
callback(function(){console.log('Successfuly invoked as an argument inside function callback')})
function foo(){
return function(){console.log('working!')};
}
var bar = foo();
bar(); // working!
var sum = function (a,b){return a+b}
sum(4,4);
It means that function actually inherits from Object. So that you can pass it around and work with it like with any other object.
In c# however you need to refrain to delegates or reflection to play around with functions. (this got much better recently with lambda expressions)