Is there a way to use constants in JavaScript?
const MY_CONSTANT = "some-value";
var CONFIG = (function() { var private = { 'MY_CONST': '1', 'ANOTHER_CONST': '2' }; return { get: function(name) { return private[name]; } }; })(); alert('MY_CONST: ' + CONFIG.get('MY_CONST')); // 1 CONFIG.MY_CONST = '2'; alert('MY_CONST: ' + CONFIG.get('MY_CONST')); // 1 CONFIG.private.MY_CONST = '2'; // error alert('MY_CONST: ' + CONFIG.get('MY_CONST')); // 1
"use strict"; var constants = Object.freeze({ "π": 3.141592653589793 , "e": 2.718281828459045 , "i": Math.sqrt(-1) }); constants.π; // -> 3.141592653589793 constants.π = 3; // -> TypeError: Cannot assign to read only property 'π' … constants.π; // -> 3.141592653589793
function MY_CONSTANT() { return "some-value"; } alert(MY_CONSTANT());
var constant = function(val) { return function() { return val; } }
This approach gives us functions instead of regular variables, but it guarantees* that no one can alter the value once it's set.
a = constant(10); a(); // 10 b = constant(20); b(); // 20