Search code examples
javascriptiife

The value of a constant variable inside IIFE is being changed outside of it? How is this possible?


I have a constant variable inside an IIFE. This variable is being returned and I don't know why it can be changed.

My code looks like this:

const main = (function(args) {
    "use strict";

    let window = args.window, document = window.document, location = window.location;
    let $ = args.jQuery || null;

    const CONSTANTS = {
        config: {
            appRoot: "http://localhost/development/.../console/",
            apiRoot: "http://localhost/development/.../api/"
        }
     }

    return {
        CONSTANTS
    };
}({ window, jQuery }));

console.log(main.CONSTANTS);
console.log(main.CONSTANTS.config.appRoot = null);  /* returns null */
console.log(main.CONSTANTS);  /* value of appRoot is null now */

Now, when I open the console and write main.CONSTANTS.config.appRoot = null, it simply returns null. I don't want this value to be changed. Am I doing something wrong? Have I missed something too basic?

Also, where is this main stored? It is not stored in the window object as typeof window.main returns undefined & typeof main returns object.


Solution

  • Maybe try Object.freeze

    const main = (function(args) {
      const CONSTANTS = Object.freeze({
        config: Object.freeze({
          appRoot: "http://localhost/development/.../console/",
          apiRoot: "http://localhost/development/.../api/"
        })
      });
    
      return Object.freeze({
        CONSTANTS
      });
    }());
    
    console.log(main.CONSTANTS);
    console.log(main.CONSTANTS.config.appRoot = null);
    console.log(main.CONSTANTS.config = null);
    console.log(main.CONSTANTS);