JavaScript doesn't have the concept of reentrancy, because for reentrancy you need a second thread to call the same function that's being paused.
With even with the yield
of example (1) the function is being paused and resumed on next iteration but you cannot have another thread call that same function again while it's paused simply because there is no other thread. If you do it inside a single thread like in the code below and call again the generator function, it returns you a new and different function. That's why it's called a generator function. So you don't call the same one.
function* foo(index) {
while (index < 2) {
yield index;
index++;
}
}
const iterator = foo(0);
console.log(iterator.next().value);
// Expected output: 0
const iterator2 = foo(0);
if (iterator === iterator2) console.log('same');
else console.log('not same function');
console.log(iterator.next().value);
// Expected output: 1
console.log(iterator2.next().value);
// Expected output: 0
Output:
> 0
> "not same function"
> 1
> 0
All in all to talk about reentrancy you need multithreading. Without multithreading answers are purely theoretical. One could argue that all JavaScript functions are reentrant, because they are not vulnerable to reentrancy issues. And another one could say they are not because they cannot be interrupted.
Even with yield
is the function being interrupted? Not really, it just returns a new generated function that will run to completion to cover one iteration.
Again it's just a theoretical discussion because even if we get it wrong nothing bad is going to happen because we don't have a second thread to call it concurrently a second time !