Imperative vs Declarative in JavaScript

Yahya Gok
2 min readAug 3, 2021
https://www.youtube.com/watch?v=-E36UNXMjnU

Imperative code is telling the computer what to do in every step with details. Versus, Declarative code is what you want the results to be.

Let’s explain those concepts with examples.

Imperative Code

Below picture is an example for imperative code, there is a function called Filtered array and this function filters out the given array. What we do here is looping over the given array and finding the number less than 10 , if number less than 10 we add that number to our empty array which we called regularArray.

Imperative Code

This function will return regularArray and that is regularArray = [1,2,7]

We described exactly what happens here so that reason makes this code imperative.

Declarative Code

let’s do the same functionality with declarative way. Here we have filteredArray function and that filters out an given array with less than number 10

Declarative Code

The result will be the array with all the numbers smaller than 10.

with this Declarative way we used built in filter method, this method did what we accomplish with just using .filter(item => item < 10 )

So that is the way how declarative works. We wanted the result to be filtered and it did without given any detailed code.

Resources

--

--