The following code pushes all the points below the limit into data, until getPoint returns null.
while ((x = getPoint()) && x < limit) {
data.push(x)
}
console.log(x, 'x should be undefined here')
In this particular case I use an assignment in a conditional, I know it looks ugly, but the question focuses on x which is not local to the block. I tried to place a let there, but it doesn't work.
Is it possible to restrict the scope of x inside the while statement?
Another working implementation would be this one, but in this case I double the test on x:
do {
let x = getPoint()
if (x && x < limit) {
data.push(x)
}
} while(x && x < limit)
or
while (true) {
let x = getPoint()
if (!x || x >= limit) {
break;
}
data.push(x)
}
or
function* getPointIterator(limit) {
let x = getPoint()
while(x && x < limit) {
yield x;
}
}
data.push(...getPointIterator(limit))
{}block for restricting lexical scopeforloop:for (let x; (x = getPoint()) && x < limit;) {}forloop{}?