Re: Javascript30


I have a Javascript30 question. Is it ok to post the question here?


Sure. We’re kind of built around FCC’s web dev curriculum, but you can bring up other things. Anything that helps people learn to be better coders is gravy.

Thanks Kevin!

I have questions for the following challenge.

This is the answer to the challenge!

The following is my answer to question # 3 of the challenge:

    // Array.prototype.sort()
    // 3. Sort the inventors by birthdate, oldest to youngest
    const inventorsBirthAscending = inventors.sort((previous,current)=>
      return previous.year - current.year})

It works but the answer is quite different. Looking for some help with what’s actually going on.

I actually like yours better. It will sort based on positive or negative, regardless of the size of the number. You are generating that through subtraction. They are generating it through returning 1 or -1 depending on which is larger. What you have is simpler. I like simple.

The other issue I have with theirs is that it doesn’t account for if they are the same. I would expect it to return 0 in that case - yours does, theirs doesn’t. I thought there was an issue if a sort callback didn’t deal with that case - I may be wrong. Maybe I’ll run some experiments later.

1 Like

I’d also suggest looking at the docs for the sort method, specifically the compare function it takes.


I figured out mine did account for 0. (I tested it)

I did look. My brain blew up a bit. I’ll try again. :sweat_smile:

With regards to my question about if there was a difference in the two approaches to the sort callback. When in doubt, test it. I wrote a little code to test it, you can see the pen here. It’s a bit ugly but it gets the job done. (Which coincidentally is how my wife describe me.)

At least in this JS implementation, the difference in speed is very rare and very trivial. Sometimes when I run it, the “using zero” version has a slight advantage, but probably not enough to matter in the astronomically vast number of cases.

This is of course assuming that “fewer calls to the callback” is best. It may also be the case that one callback is slightly more performant than the other. But that is a different test and a more complicated one.

1 Like

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.