Search code examples
javascriptscopememory-addressobject-lifetime

Caching of anonymous objects in Javascript


This is a nonsensical example used purely for illustration purposes:

function a() {
  return b().bar + foo.bar;
}

function b() {
  var foo = {
    bar: 'baz'
  };
  return foo;
}

console.log(a()); // Obviously throws a Uncaught ReferenceError: foo is not defined.

What I would like to understand is:

1) Is foo resolved as an anonymous object (Object {bar: "baz"}) in function b before returning? Or is it resolved in function a after foo is returned?

2) Since the return value of the b() call is cached temporarily in order to execute the string concatenation, would it be possible to access that anonymous object during run time, like I tried? Well, it's obviously not called "foo" anymore, but it's temporarily in the scope of function a, so the function scope knows of it's location, right?

For example:

function a() {
  return b().bar + b().bar;
}

function b() {
  var foo = {
    bar: 'baz'
  };
  return foo;
}

console.log(a()); // logs "bazbaz".

Which means the result of the first b() call is stored somewhere on the stack until the second one returns. Is it possible to refer to this object directly during run-time?


Solution

  • 1) Is foo resolved as an anonymous object (Object {bar: "baz"}) in function b before returning? Or is it resolved in function a after foo is returned?

    The identifier foo exists only within b. When you do return foo, foo's value is resolved and then set as the return value of b (whereupon that value no longer has any connection back to the identifier).

    2) Since the return value of the b() call is cached temporarily in order to execute the string concatenation, would it be possible to access that anonymous object during run time, like I tried?

    Not directly, you'd have to store that value somewhere in order to reuse it:

    function a() {
      var bval = b();
      return bval.bar + bval.bar;
    }
    

    Which means the result of the first b() call is stored somewhere on the stack until the second one returns. Is it possible to refer to this object directly during run-time?

    No, you can't directly access the stack.