patternjavascriptMinor
Defining constants in JavaScript
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:
My constant currently is
I am aware there is just one variable currently, but as this module grows there will be more.
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:
You could alternatively make a function that returns the constant.
Replacing a function (like
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.