Declarative programming is a programming paradigm … that expresses the logic of a computation without describing its control flow.
Imperative programming is a programming paradigm that uses statements that change a program’s state.
Declarative Programming is like asking your friend to draw a landscape. You don’t care how they draw it, that’s up to them.
Imperative Programming is like your friend listening to Bob Ross tell them how to paint a landscape. While good ole Bob Ross isn’t exactly commanding, he is giving them step by step directions to get the desired result.
Alright, alright, here’s some code examples. Here we just have a button that changes it’s color on click. I’ll start with the imperative example:
const container = document.getElementById(‘container’);
const btn = document.createElement(‘button’);btn.className = ‘btn red’;
btn.onclick = function(event) {
if (this.classList.contains(‘red’)) {
this.classList.remove(‘red’);
this.classList.add(‘blue’);
} else {
this.classList.remove(‘blue’);
this.classList.add(‘red’);
}
};container.appendChild(btn);
And our declarative React example:
class Button extends React.Component{ this.state = { color: 'red' } handleChange = () => {
const color = this.state.color === 'red' ? 'blue' : 'red';
this.setState({ color });
} render() {
return (<div>
<button
className=`btn ${this.state.color}`
onClick={this.handleChange}>
</button>
</div>);
}
}
The differences here may be subtle. We still have logic that says if red then blue, but there’s one huge difference. The React example never actually touches an element. it simply declares an element should be rendered given our current state. It does not actually manipulate the DOM itself.
Reaching for direct DOM manipulation is a mistake I felt myself making often when I first started working with React. It’s also a problem I’ve noticed in developers coming from a background that’s heavy in jQuery.
When writing React, it’s often good not to think of how you want to accomplish a result, but instead what the component should look like in it’s new state. This sets us up for a good control flow where state goes through a series of predictable and replicable mutations. This doesn’t just apply to components either, but also to application state. Libraries like Redux will help enforce this method of architecting, but they aren’t necessary to achieve it.
Source: https://codeburst.io/declarative-vs-imperative-programming-a8a7c93d9ad2