2

I'm reading a code snippet,

function* powers(n) {
   for (let current = n;; current *= n) {
     yield current;
   }
}

Why there is no checking condition in the for loop (see two ;;)?

Seems the code will continue to run like a while true loop. Why not using a while instead doing this. It makes code hard to read anyway.

XY L
  • 25,431
  • 14
  • 84
  • 143

2 Answers2

1

This is an example of a generator function provided in ES6.

Calling a generator function does not execute its body immediately; an iterator object for the function is returned instead. When the iterator's next() method is called, the generator function's body is executed until the first yield expression, which specifies the value to be returned from the iterator or, with yield*, delegates to another generator function.

When we call a generator function, only the part till the first yield is executed. What you have shown iterates a variable with current *= n.

Since it does not require an exit condition, it is skipped. The for loop will be executed the number of times the function is called.

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/function%2A

Agney
  • 18,522
  • 7
  • 57
  • 75
1

That's equivalent to no check at all.

If it weren't for the initialization and final (end-of-loop) expressions, it would be like while (true) { yield current; }

From MDN - for statement (emphasis mine):

condition

An expression to be evaluated before each loop iteration. If this expression evaluates to true, statement is executed. This conditional test is optional. If omitted, the condition always evaluates to true. If the expression evaluates to false, execution skips to the first expression following the for construct.

To understand the purpose of that function, you'd have to look into the yield keyword. An example of usage would be:

var p = powers(2);
console.log(p.next()); // 2
console.log(p.next()); // 4, 8, 16 and on...
acdcjunior
  • 132,397
  • 37
  • 331
  • 304