Declarative V. Imperative Programming

Sammy Kroner
2 min readFeb 13, 2021

If you’ve looked up the difference between imperative and declarative programming, you might recognize the phrase:

“imperative programming is how you do something, while declarative programming is just what you want to do”

Confused? Don’t worry. It’s a bit strange, but with a few examples and metaphors, I think we can get there.

Basically, imperative programming is what many people are used to with typical programming in things like JavaScript, where every step is explicitly laid out for your machine to execute. If you want to double every element in an array, you create a for loop that iterates through the length of the array, perform a mathematical operation on each element, then return the result.

Declarative programming is just using the map method to iterate through the array, and double each element.

Imperative programming cares about the steps we take to reach our result, while declarative programming only cares that we reach the result.

If you were telling somebody how to bake a cake, imperative programming would mean telling them where the ingredients are, when to use them, and how to use them. Declarative programming would be telling them to just bake a damn cake.

What might also help is examples of programming languages from both ends and in between

Declarative programming: HTML, SQL

Both of these programming languages let you express the logic of a computation, but the actual work flow of that computation is hidden in a black box. We don’t care how a SQL query gets done, only that it gets done.

Imperative programming: C++

C++ (the best programming language) is a great example of modern imperative programming. As a programming language, it gives the user immense control over how computations are carried out. This makes it useful for more technical, back end programming work where efficiency matters, and how and when you do something is important.

JavaScript is a mix of the two. It’s imperative, in that you can still write out the precise instructions you want to happen, but it’s declarative in that it has many helper functions that can condense and simplify your work. Rather than looping through an array to see if it contains a value from another array, you can simply use array.every, and array2.includes. You might not know exactly how it’s doing the work, but you know that it’ll tell you what you want to know.

Written by Sammy Kroner

--

--