Learn Simpli

Free Online Tutorial For Programmers, Contains a Solution For Question in Programming. Quizzes and Practice / Company / Test interview Questions.

First-class Functions in Javascript

Introduction
  1. First-class functions mean functions are treated like any other variable or value
  2. A programming language is said to have First-class functions when functions in that language are treated like any other variable
  3. A function can be passed as an argument to other functions
  4. A function can be returned by another function and can be assigned as a value to a variable
Assign function to a variable:
In JavaScript, any functions can be assigned to a variable
//Example
const message = function () {
    console.log("message");
}
// Invoke it using the variable
message();
Pass a function as an Argument
In JavaScript, we can pass a function as an argument to another function
//Example:
function sayHello() {
  return "Hello, ";
}
function greeting(helloMessage, name) {
    console.log(helloMessage() + name);
}
// Pass `sayHello` as an argument to `greeting` function
greeting(sayHello, "JavaScript!");
Return a function
A function can return another function
unction sayHello() {
    return function () {
        console.log("Hello!");
    }
}