Home > Net >  Why return keyword is used as a method?
Why return keyword is used as a method?

Time:12-30

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?

CodePudding user response:

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

  • Related