To verify if your reassignment successfully executed:
var isConst = function(name, context) {
// Check if the item exists in the context
context = context || this;
if(typeof context[name] === "undefined") return false;
// If it exists, attempting a reassignment should fail,
// either through an exception or because no change occurs.
try {
var _a = context[name];
context[name] = !context[name];
if (context[name] === _a) return true;
// Remember to revert back to original value after testing!
context[name] = _a;
} catch(e) { return true; }
return false;
}.bind(this);
A try/catch block is necessary as reassigning might result in an exception (e.g., Firefox), but when not (e.g., Chrome), ensure that your reassigned value truly changed.
Here's a simple test:
const a = 4;
var b = "lol";
isConst('a'); // -> true
isConst('b'); // -> false
If constants are declared in a different scope, provide that scope for accurate resolution of the object.
Limitation: This technique does not apply to variables declared outside of object scopes. However, it rationalizes declaring them elsewhere. For example, using const
within a function scope renders it mostly redundant:
function add(a) {
return ++a;
}
function test() {
const a = 4;
console.log(add(a));
}
test(); // -> 5
Although a
remains constant inside test()
, it transforms into a mutable value when passed elsewhere as it becomes just one component of the arguments
list.
Furthermore, a const
signifies immutability. Thus, recreating it continually due to multiple function calls dictates placing the const
variable outside the function, necessitating object scope once more.