Programming principles and design · Lesson 33 of 60 · Concept lesson · Optional
Declarative vs imperative
Imperative code spells out how to do something, step by step.
Declarative code states what result you want and lets the language or library work out the steps.
Most programs mix both styles.
Picture it
Code example
const numbers = [1, 2, 3, 4, 5, 6];
const evens = [];
for (const n of numbers) {
if (n % 2 === 0) {
evens.push(n);
}
}
console.log(evens.join(" "));
console.log(numbers.filter(n => n % 2 === 0).join(" "));Output:
2 4 6 2 4 6
Both print the even numbers. The loop says how, and filter says what.
numbers = [1, 2, 3, 4, 5, 6]
evens = []
for n in numbers:
if n % 2 == 0:
evens.append(n)
print(" ".join(map(str, evens)))
print(" ".join(str(n) for n in numbers if n % 2 == 0))Output:
2 4 6 2 4 6
Both print the even numbers. The loop says how, and the comprehension says what.
Check yourself
Pick an answer for each question. You can retry as many times as you like.
Loading the questions…