There are two kinds of code:
- Imperative code
- Declarative code
Imperative code
Imperative code tells a program what do do.
For example, if you write 1 + 1, youโre telling the program to add 1 to 1, which gives 2. This line of code is imperative because you tell the program what to do.
Another example of an imperative code is a for loop. Letโs say you have a fruitBasket with an array of fruits. You want to count the number of apples in the group.
Hereโs what you might do if you used a for loop.
const fruitBasket = ['apple', 'banana', 'pear', 'apple']let appleCount
for (let fruit of fruitBasket) { if (fruit === 'apple') { appleCount = appleCount + 1 }}
console.log(appleCount) // 2You can see how our thought processes get translated directly into codeโfirst, loop through the fruitBastket; then, check if the fruit is an apple; if the fruit is an apple, add one to appleCount.
Declarative code
Declarative code lets a program do things without worrying about implementation details. The details is often left to a function.
Hereโs the above code rewritten in a declarative form:
const fruitsBasket = ['apple', 'banana', 'pear', 'apple']const appleCount = countApples(fruitsBasket)Notice we donโt care about what happens in countApples. All we care about is countApples return the number of apples in the array passed to it.
countApples can be written with imperative code, and we would have been fine with it:
// Imperative countApplesconst countApples = array => { let appleCount
for (let fruit of array) { if (fruit === 'apple') { appleCount = appleCount + 1 } }
return appleCount}If youโre savvier with array methods, you could write countApples with the filter method and the length property. This combination is declarative because you can tell what happens at a glance, through the methods and properties used.
// Declarative countApplesconst countApples = array => array.filter(item => item === 'apple').lengthDonโt get hung up over imperative or declarative code
Declarative code is always better than imperative code, but theyโre harder to write in the beginning.
Donโt try to write declarative code from the get-go. Whatโs important is to get the program working firstโeven if you write imperative code. Once the program works, you can refactor (meaning, go back and edit your code) and change imperative code into declarative code.
Overtime, youโll begin to write declarative code automatically.
Welcome! Unfortunately, you donโt have access to this lesson. To get access, please purchase the course or enroll in Magical Dev School.
Unlock this lesson