DEV Community

Tiamiyu Sikiru Abidemi
Tiamiyu Sikiru Abidemi

Posted on

3 1

Difference between Imperative and Declarative Code

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

Heroku

This site is built on Heroku

Join the ranks of developers at Salesforce, Airbase, DEV, and more who deploy their mission critical applications on Heroku. Sign up today and launch your first app!

Get Started

Top comments (0)

The Most Contextual AI Development Assistant

Pieces.app image

Our centralized storage agent works on-device, unifying various developer tools to proactively capture and enrich useful materials, streamline collaboration, and solve complex problems through a contextual understanding of your unique workflow.

👥 Ideal for solo developers, teams, and cross-company projects

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay