3 ms·
> I also dont understand why the second version signals use of the variable any better than the classic version, esp if you declare the variable right ahead of
by BigJono 3y ago
> I also dont understand why the second version signals use of the variable any better than the classic version, esp if you declare the variable right ahead of it, but that is the classic "C" style.
Because you have no idea if the variable is used further down in the scope. Compare with something like parsing a csv file with support for quotes:
let rows = [];
let quoteMode = false;
for (char c of csvFile) {
...
}
rows is the end result, quoteMode is state only relevant to the process happening within the for loop. There's nothing past variable names to distinguish their intended use. Whereas:
const rows = parseCsv(csvFile);
makes it totally clear.
The reason something like reduce can make for nicer code is because it lets you do simple operations (probably not parsing a csv lol) inline in a way that makes the code just as clear as a function call would be, without adding a bunch of extra layers of abstraction (meaning more scrolling and flicking between tabs).
Really it's not about the reduce function at all, it's about the "const foo =". Once you see that, you can completely disregard the rest of the line if you've already read it and/or are confident you know what it's doing. It acts as a refresher in a way that a for loop doesn't. After you get past the inital shock of seeing a scary one liner (which get less and less scary as you see them more), it makes the next 20 times you read it much more pleasant.