Introduction to functional Programming
In Functional Programming, we want to express our whole program in terms of functions. Functional Programming is Declarative. Which means we focus more on what to do instead of How to do. In this article I will try to explain to you the basic of functional programming with JavaScript example.
First lets understand why Functional Programming is so important. Functional Programming enables us to
Functions are 1st Class Citizens because functions can be :
- Assigned to variables.
- Can be added to objects and arrays as well .
- Sent to other functions as an argument.
- Can be returned from other functions.
Let’s get right into it.
Non-Functional Way
let name = "Sayuri" ;
let message = "Hey, fellow devs, I am " ;
console.log(message + name)Output -> Hey, fellow devs, I am Sayuri
Functional Way
function message(name) {
return "Hey, fellow devs, I am " + name ;
}message("Sayuri")Output -> Hey, fellow devs, I am Sayuri
“ A Pure Function is a function which, Given the same input, will always return the same output.”
A Pure Function :
- Takes in at least 1 parameter.
- Return Something (A value or a function).
- Does not mutate any arguments.
Not Pure
let name = "Sayuri" ;function message(){
console.log("Hey, fellow devs, I am " + name )
}
he above code is not pure because
- → It is not taking name as a parameter.
- → It’s dealing with something in the global scope.
- → Also it’s not having a return value.
Pure Functions have no side effects which means it cannot alter anything outside the function.
Pure Function
function message(name) {
return "Hey, fellow devs, I am " + name
}
“ A higher order function is a function that takes a function as an argument, or returns a function or does both.”
const greet = function takeName (name){
return function message(msg){
return msg + name
}
}greet("Sayuri ")("Hey, fellow devs, I am ")Output -> Hey, fellow devs, I am Sayuri
Immutability means can’t be changed.
Mutation → (Bad)
const code= [ "Javascript", "Python", "React" ]
code[ 1 ] = "Node"
console.log(code)Output -> [ "Javascript", "Node", "React" ]
Immutation
const code = [ "Javascript", "Python", "React" ]
const code2 = code.map(lang=> {
if(lang=== 'Python') {
lang= 'Node';
}
return lang;
});console.log(code2)Output-> [ "Javascript", "Node", "React" ]
Last but not the Least Do not iterate using for or while/loops → Use Map, Reduce, Filter etc.
Let me your thoughts.
Originally published at https://santamaria-paul.medium.com on April 13, 2021.