Do you watch The Office? Remember when Michael Scott “declared bankruptcy” by yelling it into the open office?
He obviously didn’t know what a proper bankruptcy declaration looked like.
Unfortunately, we can be similarly confused about what “declarative code” means. So let’s take a moment and clear it up before we start yelling our declarations in front of the supply closet 📣
The Declarative—Imperative Spectrum
Indulge me for a moment and think of a thermostat.
You set a desired temperature and the system takes care of the rest.
“The air should be 71 degrees”
The system takes that declaration and turns it into 1000s of imperative instructions. “Get the temp. 72? Turn the fan and compressor on… Get the temp. 70? Turn the fan and compressor off… Get the temp. 71? wait…”
These aren’t opposites but points on a continuum. Code isn’t “declarative or imperative” but it can be “more declarative” or “more imperative”.
map() is declarative
Let’s bring it back home to arrays,
map is a declarative method.
“This array of names should look like an array of list items”
Under the hood
map makes a new array, kicks off a
for-loop, applies the iterator function to each item, and keeps checking array.length to determine when it’s done.
Take it home
All declarative code is — eventually — imperative.
Implement a declarative array method with imperative instructions —
slice are good methods to start with.
There are no right or wrong answers, just opportunities to explore.