Let’s Learn Declarative, Imperative, and Functional Programming

Alex Z
Tiny Code Lessons
Published in
2 min readJul 28, 2016

Declarative and imperative programming are two entirely different programming styles, while functional programming is a subset of declarative programming.

So let’s start with the first distinction — imperative and declarative.

Declarative programming is about describing what you’re trying to achieve, without instructing how to do it.

Let’s say you are asked to write a function that doubles all the members of an array. [1, 2, 3, 4] → [2, 4, 6, 8].

The imperative method would look something like this — it describes every step of the interior process, and has an internal state (the value of the function-scoped variable results).

The declarative method would look something like this — it has no internal state and is concerned with the result of the function. It feels no guilt about abstracting out all of its internal logistics.

You might here the phrase immutable when people talk about declarative programming. They are talking about the fact that this second function has no internal state — no variables that could be modified by subroutines.

So then what is functional programming?

Functional programming a subset of declarative programming that focuses on writing “pure functions”

A function is called ‘pure’ if all its inputs are declared as inputs — none of them are hidden — and likewise all its outputs are declared as outputs. A hidden input is any variable outside the scope of the function that is used or modified by the function at hand.

Rather than writing this:

You would write this:

The difference is subtle but you can see that this function now has an explicit return and absolutely no outside dependencies. Functional programs are much easier to debug and easier to read.

Thanks for reading!

P.S. credit/additonal reading — this article

--

--

Alex Z
Tiny Code Lessons

Software Developer + Product Manager. Interested in Travel, Culture, Economics and the Internet. Join Medium: https://tinycode.medium.com/membership