Functional Programming
Last updated
Last updated
Code runs in a very linear fashion: 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 removes any decimals on the number we place inside the brackets of floor()
and returns the new value.
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
Math.floor()
takes one parameter - the value to floor
Math.floor(3.14159)
returns 3
Math.pow()
takes two parameters - the base and the exponent, separated by commas
Math.pow(2, 3)
returns 8
console.log()
takes any number of parameters, separated by commas.
console.log("The value %d is the floored value %f.", 3, 3.14159)
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.
When a function returns a value, it is up to the programmer to decide how to use it.
The real strength in functional programming is the ability to write your own functions.