Imperative versus declarative code… what’s the difference?

Martin Novak
Frontend Weekly
Published in
3 min readFeb 11, 2018

--

Imperatively speaking

As a web developer you are likely using both paradigms with different code even if you may not be familiar with the terms. Programming languages tend to have multi-paradigm tendencies using both imperative and declarative syntax and I will use JavaScript to demonstrate that as well.

For updated information please consider my new post Imperative Vs. Declarative Programming In JavaScript or watching my new YouTube video:

Imperative paradigm

Procedural and object-oriented programming belong under imperative paradigm that you know from languages like C, C++, C#, PHP, Java and of course Assembly.

Your code focuses on creating statements that change program states by creating algorithms that tell the computer how to do things. It closely relates to how hardware works. Typically your code will make use of conditinal statements, loops and class inheritence.

Example of imperative code in JavaScript is:

class Number {  constructor (number = 0) {
this.number = number;
}

add (x) {
this.number = this.number + x;
}
}const myNumber = new Number (5);
myNumber.add (3);
console.log (myNumber.number); // 8

Declarative paradigm

Logic, functional and domain-specific languages belong under declarative paradigms and they are not always Turing-complete (they are not always universal programming languages). Examples would be HTML, XML, CSS, SQL, Prolog, Haskell, F#and Lisp.

Declarative code focuses on building logic of software without actually describing its flow. You are saying what without adding how. For example with HTML you use <img src="./image.jpg" /> to tell browser to display an image and you don’t care how it does that.

Functional programming based on lambda calculus is Turing complete, avoids states, side effects and mutation of

--

--

Martin Novak
Frontend Weekly

Martin is a product manager at work, a software developer in his free time, and an entrepreneur at heart.