HiveBrain v1.2.0
Get Started
← Back to all entries
patternjavascriptMinor

Defining constants in JavaScript

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
javascriptconstantsdefining

Problem

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.

Solution

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.

Code Snippets

var URL_KEY = 'CurrentURL';

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

Context

StackExchange Code Review Q#52607, answer score: 8

Revisions (0)

No revisions yet.