First Class Citizens in JavaScript Explained Simply

Seeing the term “first class citizen” is indeed intriguing at first, but most sucked into the rabbit hole of functional programming and leave with no real understanding of what first class citizens even do. In this blog, I’m going to provide practical knowledge of what you need to know and nothing else.

What is a “first class citizen”?

An object is a first-class citizen when it:

  1. Can be stored as a variable
  2. Can be passed as a parameter
  3. Can be returned from a function

This term is almost always used to describe functions. Essentially, a function is first-class when it can do everything a variable can do (hence why they call it a “first class citizen”).

Why are first class citizens good?

Being able to store functions as variables is what makes JavaScript an aesthetically pleasing language. “Arrow Functions” are essentially plain old functions that are stored as variables.

function hello() {
     return "hello world"           //This is OK 
}

const hello = () => return "hello world"!;   //THIS IS AWESOME

Being able to pass functions as parameter allows you to create “call backs”, so that your code does not become spaghetti. Just think of the “fn” as a function that will when hello() is ran and the code reaches fn. Essentially, any function you put in as a parameter will execute.

function hello(fn){
  fn()
}

hello(function() { console.log("hello world") })

Everybody knows that functions can return numbers, strings, objects, etc but JavaScript can also return functions.

function pikachuScream() {
  return function() {
    return "pikachu!"
  }
}

When we run pikachuScream(), we get a weird response.

[Function]

This is because we are only calling the inner function. In order to actually execute what was returned, we need to do the following:

pikachuScream()()
"pikachu!"

Leave a Reply

Your email address will not be published. Required fields are marked *