This is because JavaScript treats functions as first class primitives. Consider the following statement:
jasons_age = 20;
And the following condition:
function canDrinkInTheUS(age) {
if(age>21) {
return true;
} else {
return false;
}
}
Which you call like this:
canDrinkInTheUS(jasons_age);
Here a variable (age
) value has been assigned a value (20
), which 14 years ago canDrinkInTheUS(jasons_age)
would return false. However you are reading this answer right now at which point it would no longer be accurate. A better way to express my age is as a function. In JavaScript you can make age
a function, possibly like this (using this clever age calculator):
jasons_age_right_now = function() {
return ~~((Date.now() - new Date(1978,12,25)) / (31557600000));
};
This lets up update our canDrinkInTheUS function to take a function as it's argument:
function canDrinkInTheUS(age) {
if(age()>21) {
return true;
} else {
return false;
}
}
And to to call it we pass jasons_age_right_now
like this:
canDrinkInTheUS(jasons_age_right_now);
Note that you are not adding the ()
and the end of jasons_age_right_now
, this is because the function isn't being invoked until we are inside canDrinkInTheUS
.
Because JavaScript lets you pass functions as arguments you can even return a function that itself takes arguments like this:
anyones_age_right_now = function(date_of_birth) {
return function() {
return ~~((Date.now() - date_of_birth) / (31557600000));
};
};
Then change jasons_age_right_now
to look like this:
jasons_age_right_now = anyones_age_right_now(new Date(1978, 12, 25));
Because jasons_age_right_now
is a function then it can be passed to the updated canDrinkInTheUS()
.