Imperative Programming vs Declarative Programming

Daneesha Bartholomeusz
1 min readSep 15, 2021

--

With the popularization of React it has been started discussions about declarative programming. Let’s look at the difference between imperative and declarative programming.

In imperative programming you give the computer step by step instruction set on how to achieve the task. In declarative programming you only mention what you need to achieve.

For example if you walk into your neighbor and need some water, in the imperative paradigm you might say,

  1. Take a glass from the shelf
  2. Open the tap
  3. Hold the glass under the tap till its full
  4. Close the tap
  5. Hand me the glass

In the declarative paradigm you only need to say “Can I have some water, please”.

In imperative programming we declare how the task should be carried out. In declarative programming it is up to the program to decide how to carry out the task.

Most of C# and Java are imperative. (However some of it can be declarative).

Here’s an example taken from MS Docs for imperative programming.

var numbersOneThroughTen = new List<int> { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };var evenNumbers = new List<int>();
foreach (var number in numbersOneThroughTen)
{ if (number % 2 == 0)
{
evenNumbers.Add(number);
}
}

Here’s the same task, but this time done in declarative programming.

var numbersOneThroughTen = new List<int> { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };var evenNumbers = numbersOneThroughTen.Select(number => number % 2 == 0);

--

--

No responses yet