Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Walrus operator equivalent in JavaScript

Tags:

javascript

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.

like image 576
Peatherfed Avatar asked Apr 10 '26 00:04

Peatherfed


2 Answers

You could declare result inside of the for's scope.

for (let i = 0, result; (result = foo(i)) < N; i++) {
    // Do stuff.
}
like image 145
Nina Scholz Avatar answered Apr 12 '26 14:04

Nina Scholz


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);
    }
}
like image 36
T.J. Crowder Avatar answered Apr 12 '26 14:04

T.J. Crowder



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!