Why are functions called first-class citizens in JS? Or why are functions first class objects?

A:

Because functions in JavaScript are objects, functions have all the power of objects, and therefore can be treated as any other type of object.

When we say that functions are first class objects (first-class citizens), we mean that functions can also perform all functions of objects.

Functions are objects

JS, everything is an object, function is no exception, no more nonsense, directly test,

Functions have all the capabilities that objects have

A function is an object, and anything an object can do, a function can do. The only difference is that functions are invokable, that is, functions are called to perform an action.

object

  • Objects can be created using literals.
const obj = {}
Copy the code
  • Objects can be assigned to variables, array items, or other object properties.
const obj = {}    // Assign to a variable

const arr = []
arr.push(obj)     // Assign to an array item

obj.data = {}     // Assign attributes to other objects
Copy the code
  • Object can be used as input and output arguments to a function.
function fn (obj) {
  return {
    obj
  }
}

fn({ name: 'lin'})
Copy the code
  • Objects can create and assign properties dynamically.
const obj = {}
obj.name = 'lin'
Copy the code

function

  • Functions can be created with literals.
function fn () {}
Copy the code
  • Functions can be assigned to variables, array items, or properties of other objects.
const fn = function () {}   // Assign to a variable

const arr = []
arr.push(fn)     // Assign to an array item

const obj = {}
obj.fn = fn     // Assign attributes to other objects
Copy the code
  • Functions can be input and output arguments to functions, which is an important reason why JS has closures.
function fn (callback) {
  return callback()
}

fn(() = > {
  console.log('hello')})Copy the code
  • Functions can create and assign attributes on the fly.
function fn () {}

fn.name = 'lin'
fn.age = 18
Copy the code

Extension: Functions can assign some purpose to attributes

Function unique identifier

Giving a function an ID attribute as a unique identifier can improve performance in some cases, such as,

A function in a set that does not want duplicate functions

const store = {
  nextId: 1.cache: {},
  add (fn) {
    if(! fn.id) { fn.id =this.nextId++
      this.cache[fn.id] = fn
    }
  }
}
Copy the code

Test it out,

function fn1 () {}
function fn2 () {}

store.add(fn1)  
store.add(fn1)       // Add two identical functions
store.add(fn2)
console.log(store.cache)
Copy the code

After adding FN1 twice, only one fn1 is saved, as shown below.

This can be used to manage the collection of callback functions that need to be called after an event occurs. The functions that already exist in the collection should not be stored in the collection to improve performance.

Self memory function

By adding attributes to a function to remember some of the results of the calculation, it can be called later without recalculating, improving performance. Take calculating prime numbers as an example.

function isPrime (value) {
  if(! isPrime.cache) { isPrime.cache = {}// Add a cache to the function to remember the result
  }
  if(isPrime.cache[value] ! = =undefined) {
    console.log('It's in the cache${value}, directly returns')
    return isPrime.cache[value]  // If there is a value, return it directly
  }
  let prime = value > 2    / / calculate
  for (let i = 2; i < value; i++) {
    if (value % i === 0) {
      prime = false
      break}}console.log('Not in the cache${value}, save it in)
  return isPrime.cache[value] = prime  // If it is the first time to calculate, save the value
}
Copy the code

Test it out,

isPrime(3)
isPrime(4)
isPrime(5)
isPrime(5)
isPrime(5)    // Count 5 several times

console.log('isPrime.cache :>> ', isPrime.cache)
Copy the code

Computing prime numbers is simple computation, but if you use it for complex computation, such as computation in animation, searching for data that doesn’t change often, time-consuming math, etc., the performance improvement is huge.

summary

There are pros and cons to adding attributes to functions:

  • The advantage is that you can group all the functions that belong to this function together;
  • The downside is that purists will think that logic is mixed too much, and functions should only do one thing well

Some people do a lot of practice in purely functional programming, and some people do a lot of practice in adding properties to functions. For example, the FunctionComponent in the React source code also defines a bunch of properties on functions.

For us ordinary developers, the usual development can be used to use, that is, not to use, understand, broaden the horizon is also good.

At the end

If my article is helpful to you, your 👍 is my biggest support ^_^

I’m Allyn, export insight technology, goodbye!

The last:

How to convert pseudo-arrays into arrays in JS