Declarative vs Imperative Programming from a Front-End Perspective

Introduction

  • Declarative Programming: Tell the “machine” what you want (what), and let the machine figure out how to do it (how).
  • Imperative Programming: Command the “machine” how to do things (how), so no matter what you want (what), it will follow your commands.

How do we explain these two concepts?

Let’s use these two ideas and explain both programming paradigms with the technologies we are most familiar with.

Declarative Programming

Tell the “machine” what you want (what), and let the machine figure out how to do it (how).

...more code
</head>

<body>
    <div id="box">Declarative Programming</div>
</body>
</html>
#box {
  width: 100px;
  height: 100px;
  color: #fff;
  background: #000;
}

Imperative Programming

Command the “machine” how to do things (how), so no matter what you want (what), it will follow your commands.

var oDIv = document.createElement("div");
var text = document.createTextNode("Imperative Programming");
oDIv.appendChild(text);
oDIv.id = "box";
oDIv.style.width = 100 + "px";
oDIv.style.height = 100 + "px";
oDIv.style.color = "#FFF";
oDIv.style.background = "#000";
document.body.appendChild(oDIv);

Summary

The results of the above two examples are exactly the same.

In my opinion, behind declarative programming lies a high degree of abstraction in code implementation. Declarative programming simplifies the work.

Article Link:

/en/archive/declarative-vs-imperative-programming/

# Related Articles