Declarative programming is when you write your code in such a way that it describes what you want to do, and not how you want to do it. It is left up to the compiler to figure out the how.
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>);
}
}
https://codeburst.io/declarative-vs-imperative-programming-a8a7c93d9ad2
Use the share button below if you liked it.
It makes me smile, when I see it.