DEV Community

Umid Negmatullayev
Umid Negmatullayev

Posted on

JavaScript functions are first-class objects.

In JavaScript, functions are first-class objects (first-class citizens) where they are treated like any other variable. Functions can be stored in variables, can be passed as parameters in other functions, and can be returned from other functions.

1.Storing function in a variable

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

const res = division;
Enter fullscreen mode Exit fullscreen mode

In const res = division, we did not execute the function but reference the function.

Mostly invoking/executing the function requires () parentheses in JavaScript. Otherwise, it's a reference to the function itself

Invoking:

console.log(res(21, 7)) //3
Enter fullscreen mode Exit fullscreen mode

2.Passing function as an argument.

function multiply(a, b, fn) {
  return fn(a,b) * 3
}

const res = multiply(21, 7, division);  

console.log(res); // 9

Enter fullscreen mode Exit fullscreen mode

Here const res = multiply(21, 7, division); we are referencing division function. Clarity, in line return fn(a,b) * 3 we are not returning a function, we are invoking fn (a function reference) which divides a by b then multiplies 3 and return keyword returns the result.

3.Returning function from another function.

  function division(a) {
    return function (b) {
       return a/b;
    }
  }

  const res = division(21)
  const dividend = res(7) 

  console.log(dividend) //3
Enter fullscreen mode Exit fullscreen mode

If you don't understand or confused with what is going on in the above code that's alright, we have been using some advanced concepts there, such as higher-order functions, function closures, currying functions. And those will be explained in detail in the next article.

If you say "why don't we just do function division(a, b) { return a/b; }, it's much simpler ", you are not wrong! But currying gives us a reusability, for example:

  function division(a) {
    return function (b) {
       return a/b; 
    }
  }

  const res = division(21);

  const dividend = res(7);
  console.log(dividend); //3 

  const anotherOne = res(3);
  console.log(anotherOne); // 7

Enter fullscreen mode Exit fullscreen mode

We can keep dividing 21 by other values. Just like wiki said we can nest multiple functions, take one argument.

  function division(a) {
    return function (b) {
       return function (c) {
          return a/b/c; 
      }
    }
  }

  const res = division(12);
  const res2 = res(2); 
  const res3 = res2(2); 

  console.log(res3); //3
Enter fullscreen mode Exit fullscreen mode

(Check out the example on JS bin)[https://jsbin.com/dutufuxiza/edit?js,console]

Summary, functions in JavaScript are values, they can be stored in variables, they can be used in objects as properties or in arrays as an array element and they can be returned or passed as arguments to functions.

Top comments (0)