Javascript: final / immutable global variables?

Viewed 74863

I think I know the answer but... is there any way to prevent a global variable from being modified by later-executing <script>? I know global variables are bad in the first place, but when necessary, is there a way to make it "final" or "immutable"? Hacks / creative solutions are welcome. Thanks

15 Answers

You can use closure technique, MYGLOBALS is an object that has a function called getValue against the "globals" associative array that is out of scope for everything except MYGLOBALS instance.

var MYGLOBALS = function() {
    var globals = {
        foo : "bar",
        batz : "blah"       
    }
    return { getValue : function(s) {
            return globals[s];
        }
    }
}();
alert(MYGLOBALS.getValue("foo"));  // returns "bar"
alert(MYGLOBALS.getValue("notthere")); // returns undefined
MYGLOBALS.globals["batz"] = 'hardeehar'; // this will throw an exception as it should

yes the const is short for constant or final in some languages. google "javascript variable const" or constant to double i have even tested it myself so

const yourVar = 'your value';

thats what you are looking for.

This would be much cleaner approach

   var CONSTANTS = function() {
        var constants = { } ; //Initialize Global Space Here
        return {
            defineConstant: function(name,value)
            {
                if(constants[name])
                {
                   throw "Redeclaration of constant Not Allowed";
                }
            },
            getValue(name)
            {
               return constants[name];
            }
        } ;
    }() ;
    CONSTANTS.defineConstant('FOO','bar') ;
    console.log(CONSTANTS.getValue('FOO')) ; //Returns bar
    CONSTANTS.defineConstant('FOO','xyz') ; // throws exception as constant already defined
    CONSTANTS.getValue('XYZ') ; //returns undefined

try this:

const whatEver = 'Hello World!!!';

function foo(value){
 whatEver = value;
}

then you would call it like so...

<div onclick="foo('New Value');">Change Me First</div>
<div onclick="alert(whatEver);">Then click me After: Should Be alert "Hello World!!!"</div>

Choose a variable name which is unlikely to be overwritten by accident and trust the programmer to not do stupid things. JavaScript is not Java, so don't pretend it was.

Also, if what you really want to do is namespacing, use a self-executing function literal:

var myLibName = (function() {
    var aPrivateVar;

    function aPrivateFunction() {}

    function accessorForPrivateVar() {
        return aPrivateVar;
    }

    // public interface:
    return {
        getPrivateVar : accessorForPrivateVar
    }
})();

Conventions and good Documentation.

You can prefix your "immutable" variable with two (or more) underscores to indicate that is something not meant to be used by others and to avoid other people's variables clashing with yours.

Maybe creating a 'namespace' like __GLOBALNAMESPACE (Ugly name, I know) and then adding your variables into it (eg __GLOBALNAMESPACE.my_var) and creating a method like this one to retrieve them:

getVariable(string name){
  return __GLOBALNAMESPACE[name]
}

Just my 2 cents.

If you can use typescript, you can mark properties as readonly

The following example code makes a globally available variable immutable

Object.defineProperty(window, `env`, {
    value: Object.freeze({
        API: "https://api.mywebsite.com",
    }),
});

And it can be referenced from either window.env or just env.

Related