Functional Programming Flashcards
Introduction to core concepts of functional programming.
What is currying?
The process of returning a function from a function.
What does it mean to program functionally?
It means that we are using a paradigm in which functions can do the same thing as variables. In fact, functions can be assigned to variables, if needed.
What is the difference between imperative and declarative programming?
Imperative: concerned about how to achieve results with code. Looking at the code doesn’t tell much about what it is doing, so comments are much needed.
Declarative: concerned about what should happen. Details of how things happen are abstracted, which makes the syntax itself more comprehensive without too many comments.
“Data is immutable in functional programming.” What does that mean?
It means the original data doesn’t ever change. If you want to apply changes to a certain element, you must first make a copy of that data, using methods like Object.assign( ), or creating a function with the spread operator to create a new object and subscribe certain properties of that object, such as:
const x = (a,b) => ({
…a,
b
}),
considering we want to change the property b.
What is a pure function?
It is a function that takes an argument and returns something without changing the argument or the app state, causing side effects or setting global variables.
Explain how react uses pure functions to create element functions.
When we create the element functions we don’t directly apply changes to the DOM, causing side effects. The props, passed in as arguments, are not changed, and the app state is not affected.
What are the core functional javascript array methods? Why are they important to functional programming?
Array.map, Array.filter and Array.reduce
They can transform data without mutating the array, like splice or pop.
Map, filter and reduce are higher order functions. What does that mean?
They all expect other functions as arguments, thus they’re higher order functions.
What does the following code return?
const x = (c, a, b) => (c) ? a() : b() const hi = ()=>console.log("hi") const bye = ()=>console.log("bye")
x(true, hi, bye)
x(false, hi, bye)
Hi
Bye
What’s the difference between currying and recursion?
Currying is a function that returns a function, while recursion is a function that returns itself.
When recursion can achieve the same as a for loop, which technique should be prioritized? What could be the problem with the chosen technique? How to solve this problem?
Recursion, because it is more functional and works well wirh async calls. But we should be careful with browser call stack limitations, because not all javascript engines are optimized to work with a large amount of recursion, and that can cause errors. These errors can be avoided with stack clearing techniques and flattening out recursive calls.