Difference between Imperative and Declarative Code
Tiamiyu Sikiru Abidemi

Tiamiyu Sikiru Abidemi @abidemit

About: Javascript Frontend Developer and GDG Ibadan Organizer

Location:
Ibadan, Oyo State, Nigeria
Joined:
Jan 28, 2019

Difference between Imperative and Declarative Code

Publish Date: Jun 10 '19
9 0

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";
     });
Enter fullscreen mode Exit fullscreen mode
The above code snippet is an imperative way of solving code issue. Vanilla Javascript style.
Enter fullscreen mode Exit fullscreen mode
  • 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>

Enter fullscreen mode Exit fullscreen mode
frameworks like React and Vue uses Declarative code and Vanilla old style of adding eventlisteners.
Enter fullscreen mode Exit fullscreen mode

to be Cont'd

Give more intermediate examples.
Enter fullscreen mode Exit fullscreen mode

Comments 0 total

    Add comment