Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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!

like image 429
MikeJannino Avatar asked Aug 05 '16 20:08

MikeJannino


2 Answers

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);
like image 123
Explosion Pills Avatar answered Sep 23 '22 06:09

Explosion Pills


From MDN:

The destructuring assignment syntax is a JavaScript expression that makes it possible to extract data from arrays or objects into distinct variables.

If this data happens to be an object reference, this object reference will be copied into the new variable, or in your case constant.

Minimal example:

const orig = {
  foo: {
    bar: 1
  }
}

const { foo } = orig;

console.log(foo.bar);      // 1
console.log(orig.foo.bar); // 1

foo.bar++;

console.log(foo.bar);      // 2
console.log(orig.foo.bar); // 2
like image 24
TimoStaudinger Avatar answered Sep 23 '22 06:09

TimoStaudinger