JavaScript Interview Question #181
What is the difference between imperative and declarative JavaScript?
Advanced JavaScript, Practical Problems & Senior Interview Scenarios Senior Advanced
Quick Interview Answer
Imperative code describes the individual steps required to achieve a result. Declarative code focuses more on describing the desired transformation or outcome.
Detailed Explanation
Imperative code describes the individual steps required to achieve a result. Declarative code focuses more on describing the desired transformation or outcome.
Methods such as map, filter, and reduce often enable a more declarative style than manually controlling indexes and mutation. Neither style is universally superior; clarity, performance requirements, and the problem being solved should guide the choice.
Code Example
const numbers = [1, 2, 3, 4];
// Imperative
const doubled1 = [];
for (let i = 0; i < numbers.length; i++) {
doubled1.push(numbers[i] * 2);
}
// Declarative
const doubled2 = numbers.map(n => n * 2);