Yield inside () => {}
Short answer:
No, the
yieldoperator cannot be used inside arrow functions.
Let's break down why and how this works.
1. Reason: arrow functions cannot be generators
Arrow functions are syntactic sugar for regular functions,
but they have no context of their own (this, arguments, super, new.target)
and cannot contain yield, because yield is allowed only in the body of a generator function (function*).
That is, a generator is a separate function type, and arrow functions are a different type, and the two are not compatible.
2. Example - error
const gen = () => {
yield 1; // SyntaxError
};Error:
SyntaxError: Unexpected identifier3. The correct way - a regular generator function
If you need yield, you must declare a generator function with function*:
function* gen() {
yield 1;
yield 2;
}or in anonymous form:
const gen = function* () {
yield 'A';
yield 'B';
};This way yield can be used without errors.
4. But arrow functions can be used inside generators
For example, as helper callbacks:
function* gen() {
const nums = [1, 2, 3];
yield nums.map(n => n * 2); // the arrow is fine, no yield inside it
}
console.log(gen().next().value); // [2, 4, 6]The arrow function here is a regular one, it does not use yield, so everything works.
5. If you need "yield-like" behavior in an arrow function
Sometimes you can get by with other tools:
- use
returnin a wrapping generator; - use
async/await(for an asynchronous "yield"); - or an
Observable/ manualiterator.
For example:
async function* asyncGen() {
yield await Promise.resolve('data');
}But an arrow version like
const asyncGen = async* () => { ... } // not allowedis also still not allowed - the ES standard does not permit async* for arrows.
Summary
| Question | Answer |
|---|---|
Can yield be used in an arrow function? | No |
| Why? | yield is only allowed in the body of function* (a generator) |
| Alternative | Use function* or async function* |
| Can an arrow function be called inside a generator? | Yes, if it does not contain yield |
Can an arrow generator (*=>) be made? | No, it is not provided for by the standard |
Short Answer
Interview readyA concise answer to help you respond confidently on this topic during an interview.