Functions Are Just Variables
Explore how JavaScript functions are treated as first-class variables, allowing you to store and invoke them in arrays and objects. This lesson explains how to manage functions dynamically, helping you build more flexible and organized code for web applications.
We'll cover the following...
Functions as first-class entities
Functions in JavaScript are considered to be first class, meaning they are treated like any other variable we can make use of. This allows us to store functions as items in an array or as properties in an object.
Let’s see how this plays out in practice. Here we have four variables, each of them functions, that complete some operation on two numbers:
Functions as any other variable type
We can use these variables like any other variable type. This means we could store all of these functions in a single array, named operations, to clearly indicate the functions’ intent.
Since JavaScript treats functions as just another variable, it is possible to use the operations array’s functions by accessing them using bracket notation ([]). We can then use the () operator to invoke the function. This same logic applies to JavaScript objects:
In subsequent lessons, we will encounter something similar to the above example. Often times, functions are stored as object properties as the function directly relates to that object in some fashion. We will go over this concept in more detail in the next lesson.
Exercise #
Create an additional property (named modulo) in the operations object that computes the remainder of dividing a number by another number.