Douglas Moura

Douglas Moura

Software Engineer
Douglas Moura

Douglas Moura

I write about TypeScript, React and Node.js.

What is a first-class citizen in computer science?

Published at:Published at:Updated at:
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

1
function sum(a, b) {
2
return a + b
3
}

Assigning a constant to a function

1
const sum = (a, b) => a + b
2
3
// or
4
//
5
// const sum = function (a, b) {
6
// a + b
7
// }

Passing a function as an argument

1
function sum(a, b, callback) {
2
const result = a + b
3
4
if (typeof callback === 'function') {
5
callback(result) // pass the result as an argument of `callback`
6
}
7
8
return result
9
}
10
11
// Pass `console.log` as the callback function
12
// -------\/
13
sum(2, 2, console.log) // => 4

Return a function

1
function sum(a, b, callback) {
2
const result = a + b
3
4
if (callback) {
5
return () => callback(result)
6
}
7
8
return result
9
}
10
11
// The callback is the sum of the result with 2.
12
// ------------------\/
13
const fn = sum(2, 2, (result) => sum(2, result))
14
// ^---- Store the returned function in a variable
15
16
// Execute the function
17
// ---------\/
18
console.log(fn()) // => 6

Including a function in a data structure

1
// Store the basic operations in an object
2
const operations = {
3
sum: (a, b) => a + b,
4
sub: (a, b) => a - b,
5
mul: (a, b) => a * b,
6
div: (a, b) => a / b,
7
}

Leave a Reply

Loading comments...