DEV Community

Cover image for What is a first-class citizen in computer science?
Douglas Moura
Douglas Moura

Posted on • Edited on • Originally published at douglasmoura.dev

What is a first-class citizen in computer science?

In computer science, a first-class citizen is an entity that supports all operations available to other entities. Some of the available operations are:

  • They may be named by variables;
  • They may be passed as arguments to procedures;
  • They may be returned as the results of procedures;
  • They may be included in data structures.

It was the British computer scientist Christopher Strachey (1916-1975) who first coined this notion of first-class citizen status of elements in a programming language in the 1960s.

In JavaScript, for example, functions are first-class citizens, as all of the operations cited above can be applied to them. Let's see some examples:

A simple function definition in JavaScript

function sum(a, b) {
  return a + b
}
Enter fullscreen mode Exit fullscreen mode

Assigning a constant to a function

const sum = (a, b) => a + b

// or
// 
// const sum = function (a, b) {
//   a + b
// }
Enter fullscreen mode Exit fullscreen mode

Passing a function as an argument

function sum(a, b, callback) {
  const result = a + b

  if (typeof callback === 'function') {
    callback(result) // pass the result as an argument of `callback`
  }

  return result
}

//        Pass `console.log` as the callback function
// -------\/
sum(2, 2, console.log) // => 4
Enter fullscreen mode Exit fullscreen mode

Return a function

function sum(a, b, callback) {
  const result = a + b

  if (callback) {
    return () => callback(result)
  }

  return result
}

//            The callback is the sum of the result with 2.
// ------------------\/
const fn = sum(2, 2, (result) => sum(2, result))
//    ^---- Store the returned function in a variable

//          Execute the function
// ---------\/
console.log(fn()) // => 6
Enter fullscreen mode Exit fullscreen mode

Including a function in a data structure

// Store the basic operations in an object
const operations = {
  sum: (a, b) => a + b,
  sub: (a, b) => a - b,
  mul: (a, b) => a * b,
  div: (a, b) => a / b,
}
Enter fullscreen mode Exit fullscreen mode

Top comments (0)