So lets start off with a definition.
Declarative Programming is “a programming paradigm… that expresses the logic of a computation without describing its control flow.”
Now, there’s some dispute on some of the details, but generally what we mean by declarative programming is that there’s a focus on the parameters in which to execute certain functions or code blocks based on user input or activity.
So in React.js for example, we might tell a specific element to render only if a button has been clicked, but we only have to worry about the conditional logic which will handle the execution of predetermined code, where to render it to the DOM, and what should happen on a subsequent action.
Conversely, imperative programming is more focused on the exact set instructions given. For example, if you were writing a Jquery program, your instructions for showing a form on a button press would look something like this:
- Attach an event listener on doc ready for the button
- When the button is clicked, execute your function to find a container and append the form to the DOM
- Attach some sort of event listener on to the new DOM element to handle the next set of instructions
- When the form is submitted you want to find the exact form element, and remove it from the DOM
- Finally you would need to find the DOM element to re-append your button to and make sure there’s still an event handler attached
In React, since it’s a declarative approach, we can significantly reduce the number steps to reproduce the same functionality.
- Display your button and give it an `onClick` prop which takes in a function
- When clicked, the function will execute and set the component state to something like `showForm: true` which will in turn render the form to a predetermined container in the DOM
- On submitting the form you can pass your function to the `onSubmit` prop and when clicked, the component state would be set to `showForm: false` and subsequently remove the element from the DOM
Sometimes, this means writing a lot of conditional logic, but it’s incredibly efficient for handling the functionality of your app without using your code to give exact, specific instructions for every single piece of functionality. It’s a great way to specify certain conditions needing to be met and upon meeting those conditions, you specify the manner in which your code functions.
Leave a Reply