loading...

Difference between Imperative and Declarative Code

abidemit profile image Tiamiyu Sikiru Abidemi ・1 min read

Definition and Code Example:

  • Imperative - Implementing a procedure to follow in rendering a code function. A good basic example: let's assume we have a button with id "btn" in our html file we want to add an event listener to in changing the body background, our imperative code will look something like:
    <button id="btn">Change bgColor</button>

     let btn = document.querySelector('#btn');
     let parent = document.querySelector('body');
     btn.addEventListener('click', () => {
        parent.style.backgroundColor = "orange";
     });
The above code snippet is an imperative way of solving code issue. Vanilla Javascript style.
  • Declarative - Relying on methods or packages to handle the processes involved in rendering a code function. Also solving the above code issue in a declarative manner will look something like this.
    <button onclick="changeBgColor()">Change bgColor</button>

    <script>
        function changeBgColor() {
            let parent = document.querySelector('body');
            parent.style.backgroundColor = "orange";
        }
    </script>

frameworks like React and Vue uses Declarative code and Vanilla old style of adding eventlisteners.

to be Cont'd

Give more intermediate examples.

Posted on by:

Discussion

markdown guide