1

Looking at the Javascript revealing module pattern below, the variable "defaultValue" does not update and needs a getter to access and updated value - explained here.

Why is it then, that an array (e.g. defaultArray) does update and can be accessed without a specific getter?

Example Code:

        var go = function () {

        var defaultValue = null;
        var defaultArray = [];

        var setDefaultValue = function (newObj) {
            for (var i = 0; i < 5; i++) {

                if (i == 2) {
                    defaultValue = newObj;
                    defaultArray.push(newObj);
                }
            }
        };

        var getDefault = function () {
            return defaultValue;
        };

        return {
            defaultValue: defaultValue,
            setDefaultValue: setDefaultValue,
            getDefault: getDefault,
            defaultArray: defaultArray,
        };
    };


    window.onload = function () {

        var ans = new go();
        ans.setDefaultValue({ test: 'ok', unos: 123 })

        // At this point, defaultArray has updated, but defaultValue has not
        var thisWillBeNull = ans.defaultValue;
        var thisWillHaveAValue = ans.defaultArray;

        // Can get the value
        var newDefault = ans.getDefault();

    };
Community
  • 1
  • 1
JsAndDotNet
  • 16,260
  • 18
  • 100
  • 123
  • 4
    Because arrays are mutable objects (and you only get a reference to it), while values are immutable. – Bergi Oct 06 '14 at 16:47

1 Answers1

2

The difference is in editing the variables themselves vs. the object they reference.

When assigning one variable or property to another, the value is always copied and the variables/properties remain independent of each other.

// defaultValue: defaultValue

defaultValue ------\
                    >--- null
ans.defaultValue --/
// defaultArray: defaultArray

defaultArray ------\
                    >--- []
ans.defaultArray --/

The reassignment to defaultArray within setDefaultValue() is actually altering the variable, but doesn't have any affect on the property.

defaultValue ------- { test: 'ok', unos: 123 }

ans.defaultValue --- null

While the .push() is altering the Array instance itself, leaving both the variable and property unchanged as holding references to the Array.

defaultArray --------\
                      >--- [
                     /       0: { test: 'ok', unos: 123 }
                    /      ]
ans.defaultArray --/

By defining the property as a getter and/or setter, it will no longer hold its own value and will be dependent upon the variable:

return {
    get defaultValue() {
        return defaultValue;
    },

    // ...
};
ans.defaultValue ----> defaultValue ----> null
ans.defaultValue ----> defaultValue ----> { test: 'ok', unos: 123 }
Jonathan Lonowski
  • 121,453
  • 34
  • 200
  • 199