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.
-
not using while because it applies calaculation to current of *= nGeorge– George2018年03月23日 03:27:48 +00:00Commented Mar 23, 2018 at 3:27
-
Yes you are totally right.Jonas Wilms– Jonas Wilms2018年03月23日 03:30:19 +00:00Commented Mar 23, 2018 at 3:30
-
@nathan no, thats not in question. Please read questions more carefully.Jonas Wilms– Jonas Wilms2018年03月23日 03:31:03 +00:00Commented Mar 23, 2018 at 3:31
-
@Jonas: the only way the question makes sense is if the OP doesn’t know what yield means. Also the answers posted here so far are explaining what yield is. So I think this is a valid dupe.Nathan Hughes– Nathan Hughes2018年03月23日 03:37:42 +00:00Commented Mar 23, 2018 at 3:37
2 Answers 2
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 totrue. If the expression evaluates tofalse, 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...
Comments
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