4
\$\begingroup\$

I am aware JavaScript does not have the concept of constant variables, which in traditional languages, you would usually define as being static/class related since there's no point in having them defined in each object instance.

So we have to make do with defining regular vars in uppercase, and just treating those like constants.

But I wondered whether there's a particular style to make it clearer to other developers that this variable is a constant, other than to define it in uppercase. I have the following plugin I am writing:

    (function () {
    var URL_KEY = 'CurrentURL',
        appName = 'MyApp',
        directoryName = 'MyAppDir';

    function GUID() {
        function s4() {
            return Math.floor((1 + Math.random()) * 0x10000)
                .toString(16)
                .substring(1);
        }

        return s4() + s4() + '-' + s4() + '-' + s4() + '-' + s4() + '-' + s4() + s4() + s4();
    }

    function setURL(domain) {
        if (!domain) {
            throw 'domain parameter required';
        }

        localStorage.setItem(URL_KEY, domain);
    }

    function getURL() {
        return localStorage.getItem(URL_KEY) || null;
    }

    window.App = window.App || {
        name: appName,
        directory: directoryName,
        createGUID: function () {
            return GUID();
        },
        getURL: function () {
            return getURL();
        },
        setURL: function (newURL) {
            setURL(newURL);
        }
    };
}());

My constant currently is URL_KEY - which is blending into the regular variables which is confusing. Is there any particular style recommended to separate the constants and the regular variables?

I am aware there is just one variable currently, but as this module grows there will be more.

\$\endgroup\$
7
  • \$\begingroup\$ JavaScript does support the const keyword which can help you create constant (variables), unless I'm missing something obvious here? \$\endgroup\$ Jun 6, 2014 at 18:19
  • \$\begingroup\$ use const keyword const URL_KEY = 'CurrentURL'; \$\endgroup\$
    – user44851
    Jun 6, 2014 at 18:20
  • \$\begingroup\$ @Chirag64 const is a Mozilla-specific extension, not part of the spec. \$\endgroup\$
    – Dagg
    Jun 6, 2014 at 23:44
  • \$\begingroup\$ @Dagg Actually, it is supported in Chrome and new versions of IE as well, but I guess it wouldn't be a good idea to use it if the user base is expected to use older versions of IE. \$\endgroup\$ Jun 7, 2014 at 4:48
  • \$\begingroup\$ @Chirag64, interesting, I knew Chrome had it for a while but didn't know it landed in IE. No idea about Safari. Probably best to wait for ES6 for const. \$\endgroup\$
    – Dagg
    Jun 7, 2014 at 5:26

4 Answers 4

8
\$\begingroup\$

You could a least separate the variables declarations into constants and variables:

var URL_KEY = 'CurrentURL';

var appName = 'MyApp',
    directoryName = 'MyAppDir';

You could alternatively make a function that returns the constant.

function URL_KEY() { return 'CurrentURL'; }

Replacing a function (like URL_KEY = function() {...}) might be more of a mental barrier for some.

\$\endgroup\$
1
  • \$\begingroup\$ This is a great suggestion! The others are also great, but this is clear and concise, and to the point. Thanks. \$\endgroup\$
    – keldar
    Jun 12, 2014 at 10:11
4
\$\begingroup\$

The reason your constant is blending into the rest of your variables is that it is just another variable. The only difference is that it's capitalized.

In other languages, when you declare a constant, it's differentiated by a different keyword or a function. For example in C++, you have to say #define FOO "BAR" and in PHP you have to say define("FOO", "BAR");.

Because JavaScript doesn't exactly allow you to define keywords, we'll have to use a function, like in PHP. Even something simple like this will work:

function define(name, value){
    window.name = value;
}

But as long as we're here, we might as well have it define an actual, unwritable variable using object.defineProperty.

function define(name, value, scope){
    scope = scope || window;
    Object.defineProperty(scope, name.toUpperCase(), {'value': value, 'writable': false});
}

I added a few extra goodies, such as adding the ability to specify the scope of the constant and forcing the name to be capitalized.

Now, if we look at your code, it's a lot more clear what you're doing:

define("URL_KEY", "CurrentURL");
var appName = "MyApp";
var directoryName = "MyAppDir";
\$\endgroup\$
3
\$\begingroup\$

You could put the constants in an object. Creating a namespace of sorts makes them isolated from regular variables:

var Const = {
  urlKey: 'CurrentURL'
};
\$\endgroup\$
1
\$\begingroup\$

I have seen others attach the type of variable to the name, usually like var oMyCustomDohikey = {} That make me think you could do

var const_URL_KEY = ...
var strng_appName = ...
var array_MyList  = ...

etc. As long as you're consistent I don't see why this would be an issue...

Food for thought.

\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.