|
| 1 | + |
| 2 | +## Functions - Custom |
| 3 | + |
| 4 | +- Functions are **created/ defined** then they are **called**. |
| 5 | + |
| 6 | +- Defining a function: |
| 7 | + |
| 8 | + ```javascript |
| 9 | + // Function definition |
| 10 | + |
| 11 | + function calculateBill() { |
| 12 | + // this is the function body |
| 13 | + console.log('running calculateBill'); |
| 14 | + } |
| 15 | + |
| 16 | + ``` |
| 17 | + |
| 18 | +- Calling a function: |
| 19 | + |
| 20 | + ```javascript |
| 21 | + // Function call or run |
| 22 | + |
| 23 | + calculateBill(); // running calculateBill (returns undefined) |
| 24 | + |
| 25 | + ``` |
| 26 | + |
| 27 | +- Variables created inside a function are not available outside the function. e.g. `total` above. |
| 28 | + |
| 29 | + It is a **temporary variable.** After running of the function is complete, the variable is cleaned up or garbage-collected. |
| 30 | + |
| 31 | +- **Returning value from function:** |
| 32 | + |
| 33 | + ```javascript |
| 34 | + function calculateBill() { |
| 35 | + const total = 100 * 1.13; |
| 36 | + return total; // total is returned |
| 37 | + } |
| 38 | + |
| 39 | + calculateBill(); // returns 112.999999999 |
| 40 | + |
| 41 | + ``` |
| 42 | + |
| 43 | +- Capturing returned value from a function into a variable: |
| 44 | + |
| 45 | + `const myTotal = calculateBill();` (myTotal will have value 112.999999999) |
0 commit comments