Search code examples
javascriptnode.jssessionhttprequest

Are any aspects of object destructuring assignments by reference?


I have a program that is incrementing requests on a session cookie and printing them out to the console. Initially, I was trying to figure out how I could save this data. After logging in a couple places, I realized that the data was being saved/changed despite me having a seperate variable to hold what I thought was a temporary version of the req member object.

This is the code that made me realize that the actual object was being changes when I incremented the variable I assigned it to:

recordRequest(req) {
  const { ip } = req.info;
  const { requestsPerSecond } = req.session;
    if (req.originalUrl.split('/').filter(Boolean)[0] == 'www.example.com') {
      requestsPerSecond[ip] = requestsPerSecond[ip] + 1 || 1;
    }
  console.log(req.session.requestsPerSecond);
}

I can't seem to find in the docs here or on Mozilla whether or not this is intended behavior, whether or not this is a result of my use of const (where you can mutate member variables), or there is some kind of weird bug going on. I also had trouble reproducing this example on a smaller scale, but I verified that nothing going in or going out of the function is affecting this chunk of code.

It's not breaking my code or anything (it's actually making my life easier) but I want to understand why this is happening!


Solution

  • I would default to object destructuring working essentially the same as normal assignments. Consider:

    const req = {session: {requestsPerSecond: {"0.0.0.0": "foo"}}};
    const requestsPerSecond = req.session.requestsPerSecond;
    // updates to `requestsPerSecond` will also update `req`.
    

    I'm not sure you can use destructuring to break the assignment, so you will have to use normal tactics:

    const requestsPerSecond = Object.assign({}, req.session.requestsPerSecond);