-3

Consider the following:

class VillageState {
  constructor(place, parcels) {
    this.place = place;
    this.parcels = parcels;
  }

  move(destination) {
    if (!roadGraph[this.place].includes(destination)) {
      return this;
    } else {
      let parcels = this.parcels.map(p => {
        if (p.place != this.place) return p;
        return {place: destination, address: p.address};
      }).filter(p => p.place != p.address);
      return new VillageState(destination, parcels);
    }
  }
}

The part I'm interested in is here:

let parcels = this.parcels.map(p => {
        if (p.place != this.place) return p;
        return {place: destination, address: p.address};
      }).filter(p => p.place != p.address);

As you can see, the map function called on this.parcels, has two return statements in it. There isn't an else keyword, so I'm wondering how this behaves. Does the initial 'return p' statement return that value to the expression below it? Does it return it to the original function? Or does it allow for two conditions on each item.. as in, if p.place != this.place, return p as is, but for the rest, return an object with these properties/values? Why is the else omitted in this?

jonrsharpe
  • 115,751
  • 26
  • 228
  • 437
Jordan
  • 194
  • 1
  • 12
  • 1
    Nothing special: a `return` statement exits the function immediately. You can have 10 `return` statements if you wanted to, in an `if ... else if.... else if ....` construct. – trincot Jul 09 '20 at 19:41
  • 1
    It's the same as `if (condition) { return trueValue; } else { return falseValue; }`, but 1. the braces are optional if the `if` block only contains a single line; and 2. if the `if` block returns, you don't need an `else` (because the whole rest of the function is the `else`). – jonrsharpe Jul 09 '20 at 19:41
  • 1
    The `return` statement terminates the function call. So if the condition of `if` is the `true` the first `return` statement is used and the function call ends there. If the condition is `false`, the second `return` is used. The `else` statement could be omitted. – ibrahim mahrir Jul 09 '20 at 19:44
  • Thanks for the help I now understand it. – Jordan Jul 09 '20 at 19:48

1 Answers1

1

Actullay you are raising a concern about two approaches:

A.

if (condition) {
   // do
   // things...
}

B.

if (!condition) { return; }
// do
// things...

The rule is simple : If the function returns, it ignores every subsequent instruction.

And the answer is that they are equally efficient, but B is usually adopted to give better readability, especially when used to avoid many nested conditions.

Abdennour TOUMI
  • 87,526
  • 38
  • 249
  • 254