2

I was going through the docs and found this code:

const LIMIT = 3;

const asyncIterable = {
  [Symbol.asyncIterator]() {
    let i = 0;
    return {
      next() {
        const done = i === LIMIT;
        const value = done ? undefined : i++;
        return Promise.resolve({ value, done });
      },
      return() {
        // This will be reached if the consumer called 'break' or 'return' early in the loop.
        return { done: true };
      },
    };
  },
};

(async () => {
  for await (const num of asyncIterable) {
    console.log(num);
  }
})();
// 0
// 1
// 2

In the code above, I'm not able to understand why return used as a method like this return(){}? I tried running this code and worked fine. So, is this a new addition to JavaScript?

gacat
  • 116
  • 1
  • 13
  • 2
    Because that's how an [async iterator](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols#the_async_iterator_and_async_iterable_protocols) is specified: _"`return(value)` Optional: A function that accepts zero or one argument and returns a promise. The promise fulfills to an object conforming to the `IteratorResult` interface, and the properties have the same semantics as those of the sync iterator's."_ – Andreas Dec 29 '22 at 17:37
  • Thank you @Andreas Din't taken care of that optional but it's misleading concept in JavaScript I think. – gacat Dec 29 '22 at 17:40

1 Answers1

5

It's a method definition, not a return statement.

Similar to how, here, return is a property of object:

const object = {
    return: () => {
        return "Hello world";
    }
};

console.log(object.return()); // Hello world
jsejcksn
  • 27,667
  • 4
  • 38
  • 62
Nora Söderlund
  • 1,148
  • 2
  • 18
  • _"It's an object property, not a return statement."_ - OP already knows this: _"I'm not able to understand why return **used as a method**..."_ – Andreas Dec 29 '22 at 17:39
  • 4
    I don't get that impression from OP. They understand it's a method but doesn't understand why, considering the `return keyword` in the title. My understanding of the question is OP asking why `return` can be used as a function name. – Nora Söderlund Dec 29 '22 at 17:41
  • 3
    [^](https://stackoverflow.com/questions/74954309/why-return-keyword-is-used-as-a-method#comment132270941_74954327) @Andreas Just because it's in a specification doesn't mean that it's not a bad naming convention. I would argue that any overlap with language keywords is — at best — potentially confusing to _some developers_ (case in point: this question) – jsejcksn Dec 29 '22 at 17:41
  • @jsejcksn In this case, it's a good naming convention. On generator objects, this method does exactly what the name says, similar to the `.throw()` method they also have. – Bergi Jan 02 '23 at 09:03
  • I think this discussion proves that it's an opinion based naming convention. Which is fair and I removed my original note from the answer. – Nora Söderlund Jan 02 '23 at 18:45