Functions Explained - jpjohnsonjr/learning-notes GitHub Wiki

About

Functions are "first-class data types." That means, anything that can be done with a variable or object can also be done with a function. That means, for example:

  • Can be passed
  • Can be assigned to a variable
  • Can be passed as an argument to another function
  • Can return it as a result from a function

Functions are regular objects in Javascript.

Examples

Because functions are objects, should be possible to set properties on them. Take for example the following code:

 3 function multiply(x, y) {
 4   return x * y;
 5 }
 6 console.log(multiply(5, 3));
 7 multiply.version = "v.1.0.0";
 8 console.log(multiply.version);

This will output the following to the console:

 15         script.js:6
 v.1.0.0    script.js:8

Here are extensions of this code:

11 function(makeMultiplier(multiplier) {
12   var myFunc = function (x) {
13     return.multiplier * x;
14   };
15
16 return myFunc;
17 }
18 
19 var multiplyBy3 = makeMultiplier(3);
20 console.log(multiplyBy3(10));
21 var doubleAll = makeMultiplier(2);
22 console.log(doubleAll(100));

Above Explained:

  • Line 11 - Declares new function called makeMultiplier with one argument multiplier.
  • Line 12 - Indicates that the function will perform the task of assigning a variable called myFunc the value of the function of the variable x (declared above as an argument of the function multiply) times the value of multiplier.
  • Line 13 - Returns the value of the variable myFunc.
  • Line 19 - Declares a variable called multiplyBy3 and sets its value to makeMultiplier with an argument of 3.
  • Line 21 - Declares a variable called doubleAll and sets its value to makeMultiplier with an argument of 2.

Here's a further extension:

26 // Passing function as arguments
27 function doOperationOn(x, operation) {
28    return operation(x);
29 }
30
31 var result = doOperationOn(5, multiplyBy3);
32 console.log(result);
33 result = doOperationOn(100, doubleAll);
34 console.log(result);

Above explained:

  • Line 27 - creates a function called doOperationOn with arguments x and operation.
  • Line 28 - returns the value of operation as x.
  • Line 31 - declares a variable called result and sets its value to that of doOperationOn with arguments 5 and multiplyBy3. (Should be 15.)
  • Line 33 - returns the result of doOperationOn with arguments 100 and doubleAll. (Should be 200.)