Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

190
Views
Walrus operator equivalent in 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.

about 4 years ago · Juan Pablo Isaza
2 answers
Answer question

0

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

for (let i = 0, result; (result = foo(i)) < N; i++) {
    // Do stuff.
}
about 4 years ago · Juan Pablo Isaza Report

0

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);
    }
}

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!