Junior — Middle
How to distinguish imperative programming style from declarative, and what are their main differences?
sobes.tech AI
Answer from AI
The imperative programming style describes how to perform a task, specifying actions and changes of state step by step.
The declarative style describes what needs to be achieved without going into implementation details.
For example, in JavaScript:
// Imperative style
const numbers = [1, 2, 3, 4, 5];
const evens = [];
for (let i = 0; i < numbers.length; i++) {
if (numbers[i] % 2 === 0) {
evens.push(numbers[i]);
}
}
// Declarative style
const evens = numbers.filter(n => n % 2 === 0);
Main differences:
- Imperative code is more detailed and controls the process.
- Declarative code is shorter, easier to read and maintain.
- The declarative style is often used in functional programming and when working with databases (SQL).