Question

I searched the web to try and understand this term. I understand that 'first class functions' are functions that can be assigned to variables and 'passed around'. But I don't actually understand what this means.

So what does it mean? What are First Class Functions exactly?

Examples would be welcome.

Was it helpful?

Solution

First class functions basically means Functions as a data type just like a string,an array or a number. So in Javascript, functions are data.

You should have a look at :

What is a first class citizen function?

so you can pass functions as arguments of another function:

function map(array,fun){
    var result = [];
    for(var i=0;i<array.length;i++){
       result.push(fun(array[i]));
    }
    return result;
}

map([1,2,3],function(a){return a+1;});   //yields [2,3,4]

Here we have a function that iterate over an array and return the result of an application(passed as a parameter) on each element of the array. So the application fun is a variable therefore data.

If you compare with Java,you cant do that in java (up to 7) without writing classes,therefore functions are not first class in java <=7, unlike integers or floats or classes themself. Java(<=7) only has methods of classes,not functions.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top