Day 8 of 21 Days of Javascript
I'm now on Chapter 5 of Eloquent Javascript. I'm yet to finish the chapter but a key takeaway from today is the power of abstraction. I've blogged about this before, but came to appreciate it more today.
The basic takeaway is this: Abstractions help us manage complexity. Instead of writing low-level code directly, we can break the problem down into smaller sub-tasks, each with its own bits of code we can use to solve the bigger problem.
The book gives this example. To sum all the numbers up to 10, you could write:
let total = 0, count = 1;
while (count <= 10) {
total += count;
count += 1;
}
console.log(total);
Or you could write helper functions that help you get the result with: sum(range(1,10).
function sum(myList) {
let result =0;
for (num of myList) {
result += num;
}
return result;
}
function range(x, y) {
let resultNums = [];
for (let i = x; i <= y; i++) {
resultNums.push(i);
}
return resultNums;
}
console.log(sum(range(1, 10)));
The second version uses more lines of code. However, it's easier to understand debug, and maintain because it's structured in a way that more closely matches the way we think about the problem.