Sorting alphabetically via .sort()

Sorting alphabetically via .sort().

When I look for the examples of the sorting, I see three returns:

userData?.songs.sort((a,b) => {
    if (a.title < b.title) {
      return -1;       // first
    }

    if (a.title > b.title) {
      return 1;     //second
    }

    return 0;     // third
  })

I thought logically through and decided to use only one return.

userData?.songs.sort((a,b) => {
    if (a.title < b.title) {
      return -1;       // first and the only
    }
  })

It worked the same way as the three returns in all the codes I tried to use it in.

So, why do I have to return 3 values when it can work with only one (can it?)? In one of the articles here at the camp, I also saw an example with

.sort((a, b) => {return a - b})

So, is it correct if I make sorting with only one return like in the second code example above instead of writing 3 returns?

Hi there!

If you are doing ffc curriculum challenge’s. That are specific to the challenge instructions.

1 Like

According to the documentation, in such case result will depend on the JavaScript engine used.

1 Like

So, I should return 3 values to avoid probable bugs?

Hi
You mean it’s still OK if I sort an array like this (only one return)?
array.sort((a, b) => {if (a < b) {return -1}})

Yeah, exactly. To avoid unexpected results cover all three cases in the function.

1 Like