Functional vs. Imperative Programming

WIP

Summary of use case without fancy words like paradigm, although there is some overlap as some languages support both the below is how I have been programming.

Characteristic Imperative (Procedural) Functional (Declarative)
Langauge / Library C# React
State State changes are important. State changes are non-existent.
Primary flow control Loops, conditionals, and function (method) calls. Function calls, including recursion.
Manipulation unit Class instances (objects) Functions as first-class objects and data collections.

Code Examples

Code example by Ian Mundy

Imperative (Procedural)

1
2
3
4
5
6
7
8
9
10
11
12
13
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);

Functional (Declarative)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
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>);
}
}

References