JavaScript: Functions are First-Class Citizens

Very often you can hear that in JavaScript "Functions are first-class citizens".

All it means is that it's possible to:

  • Assign a function to a variable
  • Pass a function to another function (callback)
  • Return a function from another function

Store functions in variables

const sayHi = () => console.log('Hi!');

sayHi();
// Hi!

Pass a function to another function (callback)

function sayHi() {
  console.log('Hi!');
} 

// Whatever function, you pass to it, it's going to
// call it twice
const repeatTwice = (callback) => {
  callback();
  callback();
}

repeatTwice(sayHi);
// Hi!
// Hi!

Return a function from another function

function getSayHi(name) {
  return function() {
    return `Hi, ${name}!`
  }
}

const sayHiToJohn = getSayHi('John');
const sayHiToMary = getSayHi('Mary');

sayHiToJohn();
// Hi, John!

sayHiToMary();
// Hi, Mary!

References