Today we are gonna talk about pure functions, which is one of the core concepts of functional programming.No doubt pure functions make your life easier without affecting your application's state.
Rules for pure functions:
- The function should take in at least one argument.
- The function should return a value or another function.
- The function should not change or mutate any of its arguments. Impure functions example:
function Header(text) {
let h1 = document.createElement('h1');
h1.innerText = text;
document.body.appendChild(h1);
}
Header("Header() caused side effects");
In React, the UI is expressed with pure functions. In the following example, you can see the function doesn't mutate DOM. This function
will create a heading-one element, and it is up to some other part of the application to use that element to change the DOM:
const Header = (props) => <h1>{props.title}</h1>
Hence pure functions do not cause side effects, set global variables, or change anything about the application state.
Top comments (2)
In an impure language like Javascript you can render impure functions like
Header
pure by returning a description of the impure computation instead of running it. Then you can use functor to transform this description and monad to combine several descriptions:This way you can separate the pure realm of your program from the impure one.
This is great :)