In static languages like Java/C#, I commonly make use of constants for strings or numbers, rather than insert them into the code alone. However, I tend to avoid this practice in JavaScript. More recently, as some other coders around me have taken this approach in JS, I decided I should probably solidify either my, or their, reasoning.
There is no actual "const" declaration syntax in JavaScript. We usually just settle for an informal policy of not changing uppercase properties. But my opinion is usually to avoid them altogether, because most of their benefits are lost in JavaScript. In Java, a misspelt string will cause the program to fail when you try to run it, at which point you correct it and move on. Having a static checker where both instances are pointing to the same constant eliminates that problem, as it can be found at compile-time. But JavaScript will simply have that problem all over the place, as you're ALWAYS going to discover your spelling's correctness at run-time:
Library = { doThing: function() }
setTimeout(function()
Liberry.doThing()
// No such object: Liberry
}, 0);
The best safeguard against this, usually, is "use strict". For developers that prefer it, I'm fine with them using that to find issues with undeclared variables more quickly. But my opinion has been that providing string constants for REST APIs, etc., doesn't actually safeguard you against anything. Another example:
CompanyAPI.constants.ENROLL_URL = "/rest/enroll";
CompanyAPI.constants.FIRST_NAME = "firstName";
ajax({url: CompanyAPI.constants.ENROLL_URL,
data: CompanyAPI.constants.FIRST_NAME
});
// vs.
ajax({url: "/rest/enroll",
data: "firstName"
});
...You meant to write the above, but then made typos. Whoops.
ajax({url: CompanyAPI.constants.ENROL_URL,
data: CompanyAPI.constants.FIRS_NAME
});
// vs.
ajax({url: "/rest/enrol",
data: "firsName"
});
The constant-based one will still provide undefined, while "firsName" is no better. To that end, I tend to just see this as a benefit of static languages, and not bother having a system to fix it (besides maybe starting to use "use strict" for debugging). Can some other people tell me what their preferred practice for string/integer constancy is?
EDIT: To clarify, my preference is usually to put strings like "firstName" directly inline with no top-level constant declaration - the penalties for misspelling it are the same either way. Strings that might get long, like a REST URL, I'll tend to define at the top of the file.
FIRST_NAME
? That looks like it comes from something server-side and is passed into the javascript. And that combined with you saying you come from Java/C#, I have the feeling you're misreading what these variables are for: Separating the data from the code, so that the.js
file can be cached by the browser... – Izkata Jul 22 at 0:43FIRST_NAME
in particular that had me wondering - does it not change per user? – Izkata Jul 22 at 15:15