Is there an equivalent of Python's walrus operator ':=' in JavaScript? I know it's possible to do:
for (let i = 0; (result = foo(i)) < N; i++) {
// Do stuff.
}
but I want result to be constrained to the scope of the for-loop.
You could declare result inside of the for's scope.
for (let i = 0, result; (result = foo(i)) < N; i++) {
// Do stuff.
}
Just as an alternative to Nina's good approach: Any time you want to have a variable in a narrower scope than its surroundings, you can also use a freestanding block:
{
let result;
// ...
}
That would free you from using for without an increment expression (I'm of the school that all three parts of a for should be used, or use a different loop):
{
let i = 0, result;
while ((result = foo(i++)) < N) {
// Do stuff...
}
}
Live Example:
const foo = x => x;
const N = 5;
{
let i = 0, result;
while ((result = foo(i++)) < N) {
// Do stuff...
console.log(result);
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With