Member-only story
Why do we call ReactJs declarative?

If you have coded in ReactJs, or if you are coding in it. Then you must have heard of these two terms, Declarative and Imperative.
Even, on the official site of ReactJs, it is mentioned that one of its usefulness is Declarative (others are Component-Based and Learn Once, Write Anywhere).
But why do we call it declarative and not imperative? So with that question let’s start our blog.
Hey! 👋 everyone, my name is Himanshu Singh. Currently, I am in college and nowadays I am learning web development in neogCamp.
In this blog, We will get to know why ReactJs is a declarative way of programming.
❓Imperative and Declarative
First lets we discuss, what is an imperative way of programming and a declarative way of programming.
In the Imperative way of programming, we write each step that will lead us to the desired result. Like, suppose we want to find the sum of all the elements of an Array. So, to do that we will do something like the below code, in Javascript
const sumOfArrayElements = (array) => {
let sum = 0;
for (let element of array) {
sum += element;
}
return sum;
}
Here, we can see that we have explicitly written each step required to get the sum.
Steps are:
- Initialize the variable that will store the sum
- Iterate over the array and add each element present in the array to the sum variable
- return the sum
Now, before discussing how we can improve this? let’s discuss how we will do this in a Declarative way of programming.
So, in JavaScript, we can do something like this
// const array = [1, 2, 3];
array.reduce((sum, element) => sum + element, 0);
That’s it. One line code and we will get the sum of all the elements.
Did you see it? declarative program abstracts out the code. Now we are only saying What we want, for each element of the array run the reducer function ((sum, element ) ⇒ sum + element), where the initial value of the sum is 0.