Junior — Middle
Can you explain what is meant by imperative programming style?
sobes.tech AI
Answer from AI
The imperative programming style is an approach where the developer explicitly describes the sequence of steps and state changes to achieve a result.
Unlike the declarative style, which describes what needs to be done, the imperative style focuses on how to do it.
An example of imperative code in JavaScript for summing array elements:
const numbers = [1, 2, 3, 4, 5];
let sum = 0;
for (let i = 0; i < numbers.length; i++) {
sum += numbers[i];
}
console.log(sum); // 15
Here, it is explicitly shown how to iterate over the array and accumulate the sum. This style is often used for control over the process and optimization but may be less expressive compared to functional or declarative styles.