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
makeMultiplierwith one argumentmultiplier. - Line 12 - Indicates that the function will perform the task of assigning a variable called
myFuncthe value of the function of the variablex(declared above as an argument of the functionmultiply) times the value of multiplier. - Line 13 - Returns the value of the variable
myFunc. - Line 19 - Declares a variable called
multiplyBy3and sets its value tomakeMultiplierwith an argument of3. - Line 21 - Declares a variable called
doubleAlland sets its value tomakeMultiplierwith an argument of2.
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
doOperationOnwith argumentsxandoperation. - Line 28 - returns the value of operation as
x. - Line 31 - declares a variable called
resultand sets its value to that ofdoOperationOnwith arguments5andmultiplyBy3. (Should be15.) - Line 33 - returns the result of
doOperationOnwith arguments100anddoubleAll. (Should be200.)