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?

2
  • 2
    Because that's how an async iterator 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, 2022 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, 2022 at 17:40

1 Answer 1

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

5
  • "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, 2022 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. Dec 29, 2022 at 17:41
  • 3
    ^ @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, 2022 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 2 at 9: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. Jan 2 at 18:45

Not the answer you're looking for? Browse other questions tagged or ask your own question.