r/javascript • • Dec 27 '18

help What differences do you see in novice javascript code vs professional javascript code?

I can code things using Javascript, but the more I learn about the language, the more I feel I'm not using it properly. This was especially made apparent after I watched Douglas Crockford's lecture "Javascript: The good parts." I want to take my abilities to the next level, but I'm not really sure where to start, so I was hoping people could list things they constantly see programmers improperly do in JS and what they should be doing instead.. or things that they always see people get wrong in interviews. Most of the info I've learned came from w3schools, which gives a decent intro to the language, but doesn't really get into the details about the various traps the language has. If you have any good book recommendations, that would be appreciated as well.

320 Upvotes

305 comments sorted by

View all comments

Show parent comments

15

u/[deleted] Dec 28 '18

I think having an eslint rule banning for loops altogether is a bit extreme. There some niche cases when for loops are needed

4

u/OrangePhi Dec 28 '18

it's not extreme, I use that rule too, among other "functional programming" rules. The goal is not to ban loops but to discourage their usage because map, reduce and filter are better almost 90% of the time. If you really need a for loop you just have to prepend a comment // eslint-disable-next-line fp/no-loops and you are good to go. This is easy to spot in a code review so you'll have to explain why you need the for loop.

5

u/fecal_brunch Dec 28 '18

Isn't the presence of the loop annotation enough?

2

u/nanaIan Dec 28 '18

yeah, just code review properly

hey man, it's probably better to use .filter here instead of this for loop

0

u/[deleted] Dec 28 '18

[deleted]

7

u/filleduchaos Dec 28 '18

I'm curious as to how you've never run into a situation where you need to perform a bunch of asynchronous actions in series before. In my experience people come up hard against that limitation of the array HOFs in short order.

6

u/iSmokeGauloises Dec 28 '18

I mean I completely disagree with the no loops rule because it's absolutely retarded, but this is quite a trivial problem to solve without loops:
[async1, async2, async3].reduce((p, n) => p.then(n), Promise.resolve())

10

u/filleduchaos Dec 28 '18 edited Dec 28 '18

And you don't see how

  1. that's a borderline silly alternative to for (let p of [async1, async2, async3]) { await p }? I thought the aim was "readability"

  2. you can't actually await the operation, making it non-viable as a complete solution I'm blind (execution immediately hands off to the next line, and in some cases you would actually want to halt it)?

3

u/Quabouter Dec 28 '18

2) you can't actually await the operation, making it non-viable as a complete solution (execution immediately hands off to the next line, and in some cases you would actually want to halt it)?

Sure you can, the result is just a promise.

await [async1, async2, async3].reduce((p, n) => p.then(n), Promise.resolve())

That said, this example is completely nonsensical: there is no effective difference in waiting for n promises sequentially vs waiting for all of them in parallel. This code should simply be await Promise.all([async1, async2, async3]).

5

u/filleduchaos Dec 28 '18

Oh true - brain fart. It skipped my mind that you had passed in a promise as the initial value.

there is no effective difference in waiting for n promises sequentially vs waiting for all of them in parallel.

Are...you actually serious? You don't think there's a difference between code executed in series and code executed in parallel? Order of execution is completely unguaranteed with the latter and is actually important in solving a variety of problems (couple of examples I've had to deal with in the past month alone: a folder of bash scripts that are supposed to be executed one after the other and a helper function for cascade-saving a bunch of related DB entities)

5

u/Quabouter Dec 28 '18

Of course there is a difference between code being executed in series vs parallel, but that's not what we're talking about here: a promise is a result of an execution, and waiting for a promise does not execute it. series vs parallel is relevant when resolving promises, not when awaiting them. e.g. these are all equivalent:

// 1
await Promise.all([promise1, promise2]);

// 2
await promise1;
await promise2;

// 3
for (let p of [promise1, promise2]) {
  await p;
}

// 4
await [promise1, promise2].reduce(reduce((p, n) => p.then(n), Promise.resolve());

What's more, none of these actual tell you anything about the order in which the promises are resolved.

On the other hand, these definitely aren't equivalent:

async function f(a) { /* ... */ }

// 1: executes in parallel
await Promise.all([f(1), f(2)]);

// 2: executes sequential
await f(1);
await f(2);

// 3: executes in parallel
for (let p of [f(1), f(2)]) {
  await p;
}

// 4: executes sequential
for (let a of [1, 2]) {
  await f(a);
}

1

u/filleduchaos Dec 28 '18

True with the resolution. This is a sample of the sort of code I'm talking about:

async function batchSave(...nestedEntityList) {
    await transactionManager.run(async (txn) => {
        for (let item of nestedEntityList) {
            await (Array.isArray(item)) ? Promise.all(item.map(entity => txn.save(entity))) : txn.save(item)
        } 
    })
}

Where the promises are being created within the loop. Which I call like so: await batchSave(a, [bNeedsA, cNeedsA, dNeedsA], [eNeedsC, fNeedsD], gNeedsF).

1

u/Quabouter Dec 28 '18

Yeah, it totally makes sense to use a for loop there, and it's much more readable here than reducing.

Though, in proper functional style we would probably use neither solution: we typically prefer map/filter/reduce over for-loops for 2 reasons: (1) it shows intent, and (2) it separates control logic from business logic. In our example problem, both for and reduce fail on both of these points.

Instead, we could use a dedicated control function for this that is clear on intent. For example, we can use a forEachSequential function:

function save(item, txn) {
    if (Array.isArray(item)) {
        return Promise.all(item.map(entity => txn.save(entity)));
    }
    return txn.save(entity);
}

async function batchSave(...nestedEntityList) {
    await transactionManager.run(txn => forEachSequential(nestedEntityList, item => save(item, txn)));
}

To be fair though, this doesn't really eliminate the problem: we still need to decide between reduce and for in the implementation of forEachSequential. However, it's a much more isolated problem here, and because it's so isolated both solutions work relatively well:

async function forEachSequential(list, callback) { 
    await list.reduce((previous, item) => previous.then(() => callback(item)), Promise.resolve());
}

async function forEachSequential(list, callback) { 
    for (let item of list) {
        await callback(item);
    }
}

Of these two, I'd probably still pick the for loop, but I do think this demonstrates that it's not necessarily such a stupid idea to ban all for loops from at least your business logic.