Imperative vs Declarative Programming

RanveerSequeira
2 min readMay 16, 2021

--

“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.

  1. 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]
  2. 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
  3. Using jQuery (or vanilla JavaScript), add a click event handler to the element which has an id of btn. When clicked, toggle (add or remove) the highlight class as well as change the text to Add Highlight or Remove 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/

--

--

RanveerSequeira
RanveerSequeira

Written by RanveerSequeira

AI generate Content I like to save as article

No responses yet