Imperative vs Declarative Programming
“You know, imperative programming is like how you do something, and declarative programming is more like what you do, or something.”
Let’s understand this by Examples.
1. Assume you’re at college/work. You have to reach home.
IMPERATIVE APPROACH (HOW)— Firstly get out of the building. Go to north 100 m. Turn left walk 40 m. Further head toward the big temple. Go in the small street next to the temple.Walk 70 m more. (happy Home).
P.S — Don’t come to my home go to yours.
DECLARATIVE APPROACH(WHAT) — Take a taxi and told him the address.
Still confused? Let's talk code then.
- Write a function called
double
which takes in an array of numbers and returns a new array after doubling every item in that array.double([1,2,3]) // [2,4,6]
- Write a function called
add
which takes in an array and returns the result of adding up every item in the array.add([1,2,3]) // 6
- Using jQuery (or vanilla JavaScript), add a
click
event handler to the element which has anid
ofbtn
. When clicked, toggle (add or remove) thehighlight
class as well as change the text toAdd Highlight
orRemove Highlight
depending on the current state of the element.
Imperative —
function double (arr) {
let results = []
for (let i = 0; i < arr.length; i++){
results.push(arr[i] * 2)
}
return results
}function add (arr) {
let result = 0
for (let i = 0; i < arr.length; i++){
result += arr[i]
}
return result
}$("#btn").click(function() {
$(this).toggleClass("highlight")
$(this).text() === 'Add Highlight'
? $(this).text('Remove Highlight')
: $(this).text('Add Highlight')
})
Declarative —
function double (arr) {
return arr.map((item) => item * 2)
}function add (arr) {
return arr.reduce((prev, current) => prev + current, 0)
}<Btn
onToggleHighlight={this.handleToggleHighlight}
highlight={this.state.highlight}>
{this.state.buttonText}
</Btn>
Still don’t get it. Read the full post https://ui.dev/imperative-vs-declarative-programming/