What is the declarative approach?
Declarative approach is a programming style in which you describe what should be done**, not** how exactly to do it step by step**.**
Simple definition
Declarative approach = "What I want to get" Imperative approach = "How I want to get it"
Example in JavaScript
Imperative style:
(you control the process - how exactly to reach the goal)
const numbers = [1, 2, 3, 4, 5];
const doubled = [];
for (let i = 0; i < numbers.length; i++) {
doubled.push(numbers[i] * 2);
}
console.log(doubled);Declarative style:
(you simply describe what you want to get)
const numbers = [1, 2, 3, 4, 5];
const doubled = numbers.map(n => n * 2);
console.log(doubled);Here you do not explain "how exactly to iterate the array", you simply say: "I want an array where each element is multiplied by 2".
Another example - working with the DOM
Imperative (plain JS):
const el = document.createElement("h1");
el.textContent = "Hello, world!";
document.body.appendChild(el);Declarative (React):
function App() {
return <h1>Hello, world!</h1>;
}You do not describe the process of creating and inserting the element into the DOM - React does it for you.
Where the declarative approach is used
- React - the UI is described declaratively through JSX
- SQL - "Select all rows where age > 18" (not how to iterate the table)
- CSS - "Make the text red" (not instructions for rendering pixels)
- HTML - "Here is a heading, here is a button" (not how to render them)
Advantages of the declarative approach
The code is easier to read and understand - "what" matters more than "how" Fewer errors related to manual state management Easier to scale and maintain Easier to test, because each component can be treated as a pure function
Short Answer
Interview readyA concise answer to help you respond confidently on this topic during an interview.