Sobes.tech
Middle+

There is code with an IIFE that returns an object with a value field and a setValue method. What will be printed to the console after calling setValue(2) and accessing the value field? What needs to be fixed for 2 to be printed?

sobes.tech AI

Answer from AI

Let's consider an example of an IIFE that returns an object with a value field and a setValue method:

const obj = (function() {
  let value = 1;
  return {
    value: value,
    setValue(newValue) {
      value = newValue;
    }
  };
})();

obj.setValue(2);
console.log(obj.value); // What will it output?

In the console, it will output 1, not 2. The reason is that the value field in the returned object is a copy of the value variable at the moment of object creation (which is 1). When calling setValue, the local value variable inside the closure is changed, but obj.value does not update because it is just a value, not a reference.

To fix this and get the current value, you can make value a getter:

const obj = (function() {
  let value = 1;
  return {
    get value() {
      return value;
    },
    setValue(newValue) {
      value = newValue;
    }
  };
})();

obj.setValue(2);
console.log(obj.value); // 2

Now, obj.value is a getter that returns the current value of the value variable from the closure, and after calling setValue(2), the console will output 2.

There is code with an IIFE that returns an object… - sobes.tech