1

Came across this piece of code recently:

const fetchMock = async (name, type="success") => {
  const response = await fetch(someUrl);
  let mock = await response.json();
  mock = mock[type];
  mock.json = () => mock.data;
  return mock;
}

I have trouble understanding why, on line 5, we use a function to assign the mock.data to mock.json. Can't we simply write mock.json = mock.data? How is it different?

P. S. I don't have any idea about the kind of data it is receiving.

internet
  • 303
  • 3
  • 19
  • 1
    Maybe because a library or another part of the code expects the `mock` to have a function named `json`, so they can call it as a function – Saeed Jun 02 '18 at 06:27

1 Answers1

2

Your question has nothing to do with the async JSON fetching stuff. In the end, mock is just an object which has a data property. It also needs a json property that yields the data property.

So a reduced code sample would look like this:

const mock = {
  data: {
    "someKey": "someValue"
  }
};

mock.json = () => mock.data;

Assume that mock.json is set exactly once, and mock.data is mutated or updated. Then, mock.json = mock.data will only work correctly if mock.data is an object that stays the same reference.

const mock = {
  data: {
    "someKey": "someValue"
  }
};

mock.json = mock.data;
console.log(mock.json); // { "someKey": "someValue" }, as expected
// …
mock.data.someKey = "someOtherValue"
console.log(mock.json); // { "someKey": "someOtherValue" }, as expected

// Either of these reassignments will break up the connection between `mock.json` and `mock.data`:
mock.data = {"newKey": "something"};
mock.data = "Something else";

console.log(mock.json); // { "someKey": "someOtherValue" }, no longer updated

This doesn’t matter for mock.json = () => mock.data, though, as the function just returns the current value of mock.data.

Sebastian Simon
  • 18,263
  • 7
  • 55
  • 75
  • Thanks! That seems accurate. I guess I have to properly read how passing by values and reference works. Since JS is the only language I know, it's hard to get when people try to explain things in JS by comparing with other languages, so the link didn't help me much. But I got the point. – internet Jun 02 '18 at 08:17