Functions Are Just Variables
Get an overview of JavaScript as first-class entities, enabling their storage in arrays or objects like any other variable type, facilitating dynamic invocation and usage throughout code.
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:
var sum = function(x, y){ return x + y; };var subtract = function(x, y){ return x - y; };var multiply = function(x, y){ return x * y; };var divide = function(x, y){ return x / y; };
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.
//functions can be stored in an arrayvar operations = [sum, subtract, multiply, divide];//functions can be called from an array by accessing them and using the () operatorfor(var i = 0; i < operations.length; i++){console.log(operations[i](5,10));}
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:
//functions can be stored in an object as property valuesvar operations = {sum: function(x, y){ return x + y; },subtract: function(x, y){ return x - y; },multiply: function(x, y){ return x * y; },divide: function(x, y){ return x / y; }};//functions can be called from an object by accessing a property (dot or bracket)//and using then the () operatorconsole.log(operations.multiply(5, 10));console.log(operations["multiply"](5, 10));
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.
//write your code here