JavaScript First Class Function

Md. Abdullah Al Mahmud Khan
Oceanize Lab Geeks
Published in
2 min readApr 30, 2019

JavaScript is one of the most popular languages which claims to feature “First Class Functions. JavaScript meets the bellowing points for first class function feature.

  1. A function can be stored in a variable
  2. Function can be stored in an Array
  3. Function can be stored as an Object Field or Property
  4. We can create function as needed
  5. We can pass function as an arguments
  6. We can return function from another function
  7. Function can be stored in a variable

function sum(a, b) {
return a + b;
}

var total = sum
console.log(total(10+2)); // Output will be 12

2. Function can be stored in an Array

function sum (a,b){
return a+b;
}

function div (a,b){
return a/b;
}

var arr = [1, 2, 3, sum];
arr.push(div)
console.log(arr) //[ 1, 2, 3, [λ: sum], [λ: div] ]

3. Function can be stored as an Object Field or Property

var user = {
name: “John”,
age: 24,
print: function () {
console.log(‘Hi’);
}
};

console.log(user); //{ name: ‘John’, age: 24, print: [λ: print] }

4. We can create function as needed

var multiply = 5 * (function () {
return 5
})();
multiply; //output will be 25

5. We can pass function as an arguments

function functionOne(x) {
console.log(“Hi “ + x);
}

function functionTwo(name, callback) {
callback(name);
}

functionTwo(“Sumon”, functionOne); // Hi Sumon

6. We can return function from another function

function add() {
var counter = 9;

return function(){
counter += 1;

return counter;
}
}

var result = add();
var number = result;

console.log(number()); // output will be 10
console.log(add()()); // output will be 10

Tank you very much for reading this post.

--

--