Functional Programming in Javascript - Imperative and Declarative
Pramila Dalavai
Posted on September 5, 2020
Hello there, in this post I will be talking about the imperative and declarative concepts. Whenever you have attempted to reduce or map the array without your knowledge, you are good to go to be a functional programmer in javascript. React, Flux, and redux all these are functional programming javascript frameworks.
Now talking of Declarative, its when your application is structured in a way that prioritizes describing what should happen over defining how it should happen.
It would be easier if you compare the imperative and declarative examples here:
var string = "hi there , I'm a web developer";
var removeSpace = "";
for (var i = 0; i < i.string.length; i++) {
if (string[i] === " ") removeSpace += "-";
else removeSpace += string[i];
}
console.log(removeSpace);
In this example, we loop through every character in the string, replacing spaces as they occur. Just looking at the code, it doesn't say much. Imperative requires lots of comments in order to understand code. Whereas in the declarative program, the syntax itself describes what should happen and the details of how things happen are abstracted way.
const string = "Hi there, I'm a web developer ";
const removeSpaces = string.replace(//g,"-");
console.log(removeSpaces);
Isn't this looks more readable and easier to reason about?
Now, let’s consider the task of building a document object model, or DOM. An imperative approach would be concerned with how the DOM is constructed:
var headline = document.createElement('h1');
headline.innerText = "Hello World";
It would be very hard to make changes, add features, or scale 10,000 lines of code where the DOM is constructed imperatively.
Now let’s take a look at how we can construct a DOM declaratively using a React component:
const { render } = ReactDOM
const Welcome = () => (
<div id="App">
//your HTML code
//your react components
</div>
)
render(
<App />,
document.getElementById('home')
)
React is declarative. Here, the Welcome component describes the DOM that should be rendered. The
render function uses the instructions declared in the component to build the DOM, abstracting away
the details of how the DOM is to be rendered. We can clearly see that we want to render our
Welcome component into the element with the ID of 'target'.
Posted on September 5, 2020
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.