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.
const
keyword which can help you create constant (variables), unless I'm missing something obvious here? \$\endgroup\$const URL_KEY = 'CurrentURL';
\$\endgroup\$const
. \$\endgroup\$