0

I have been playing around with dynamic assignment of routes in express and stumbled into unexpected behavior from for ... of loop.

My idea was simple:

  1. Create simple array

    const roomsArray = ["Algebra", "Backend", "Frontend"];

  2. loop through that array and create a route for each item in array, so I tried with for ... of loop

     router.get(`/room/${i}`, isUser, (req, res) => {
       res.render("index/room", { path: "index/room", name: i });
     })
    } ```
    

And the result was more than unexpected(to me at least). Each route was created as expected, but whichever route I would test, value of i assigned to name was always value of last item in array.

Switching over to for loop or forEach solves the issue and everything behaves as expected, however I would like to know why does this behavior occur using for ... of statement?

1 Answers1

2

You could have shown the loop perhaps. Based on the description you probably have var:

for(var x of [1,2,3])
  setTimeout(()=>console.log(x),0);

and could just have let instead for a fix:

for(let x of [1,2,3])
  setTimeout(()=>console.log(x),0);

let is scoped at block level, so each callback sees a separate variable. var is scoped at function-level (or here, globally), so each callbacks see the same variable with the last value inside.

tevemadar
  • 12,389
  • 3
  • 21
  • 49