# Functional Programming

Code runs in a very linear fashion:\
&#x20;<img src="https://1200419583-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-LKbpNQDFNJap9OTDSt6%2F-LR2Bwi2Ybv-Ax1I0zdx%2F-LR2G_-FsPGH7guMovVg%2FCode%20Snippet.gif?alt=media&#x26;token=775b66be-8cdb-4cf7-b525-7b8629e19739" alt="" data-size="original"> One line at a time, moving to the next.

The only method we have to repeat code is with a loop. This can create very long code files with a lot of repetition. What if you need to create a new mathematical operation and use it many times throughout the course of your program?

**Functional Programming** is a way of creating blocks (chunks) of code that you can use whenever you need. You can "call" a function that does some work and may or may not *return* a value.

We have been making calls to functions this entire time with `console.log()` and `Math.floor()` (for examples). When we ask the console to `log()` we have to put text inside the round brackets. The console prints out that text for us. When we call the `floor()` function, the [huge chunk of code we call Math](https://chromium.googlesource.com/v8/v8/+/4.3.21/src/math.js?autodive=0%2F%2F) removes any decimals on the number we place inside the brackets of `floor()` and *returns* the new value.

### Parameters

The value(s) placed inside the brackets of a function are called *parameters*. They are also called *inputs*.\
**Examples:**

* `console.clear()` takes zero parameters - it just does the job<br>
* `Math.floor()` takes one parameter - the value to floor
  * `Math.floor(3.14159)` returns 3<br>
* `Math.pow()` takes two parameters - the base and the exponent, separated by commas
  * `Math.pow(2, 3)` returns 8<br>
* `console.log()` takes any number of parameters, separated by commas.
  * `console.log("The value %d is the floored value %f.", 3, 3.14159)`

### Return Values

Some functions (not all) give back data - a number, some text, an array, etc... This is called a ***return value***. This value can either be used or ignored. Consider this - when you insert money into a vending machine, it returns either your money or a treat. When you throw money into a wish fountain, you do not receive anything tangible in return.

![](https://1200419583-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-LKbpNQDFNJap9OTDSt6%2F-LR2Bwi2Ybv-Ax1I0zdx%2F-LR2P1fM4-1TFwqC0Qtc%2FFunctions%201.png?alt=media\&token=3ae25703-9110-44ba-8b0e-7551b21ce20b)

When a function returns a value, it is up to the programmer to decide how to use it.

```javascript
Math.floor(6.87);               // The output 6 will go NOWHERE

let ans = Math.floor(6.87);     // The output 6 will be stored in the variable ans

console.log(Math.floor(6.87));  // The output 6 will go into the log() function
```

The real strength in functional programming is the ability to ***write your own functions***.
