I know I can find out if a value is var
const
or let
by looking at where it is declared. However I am wondering - mainly for debugging, developing JS compilers, and academic interest - if it is possible to find out the immutability / scope of a variable (var / const / let-ness) after it has been created.
ie
doThing(something)
Would return
let
Or equivalent. Like we can determine types with typeof
or something.constructor.name
for constructors.
let and const are block-scope variable declarations that can replace 'var' declarations in many cases.
ES6 also introduces a third keyword that you can use alongside let : const . Variables declared with const are just like let except that you can't assign to them, except at the point where they're declared. It's a SyntaxError . Sensibly enough, you can't declare a const without giving it a value.
You can distinguish let
and const
from var
with direct eval
in the same function as the variable:
let a;
try {
eval('var a');
// it was undeclared or declared using var
} catch (error) {
// it was let/const
}
As @JonasWilms had written earlier, you can distinguish let
from const
by attempting assignment:
{
let x = 5;
const original = x;
let isConst = false;
try {
x = 'anything';
x = original;
} catch (err) {
isConst = true;
}
console.log(isConst ? 'const x' : 'let x');
}
{
const x = 5;
const original = x;
let isConst = false;
try {
x = 'anything';
x = original;
} catch (err) {
isConst = true;
}
console.log(isConst ? 'const x' : 'let x');
}
let and var are only about the scope, so it's not possible. Because JavaScript does not pass by reference, if you were to pass a variable to a function you would lose the " constness" and also the scope - on that function the variable would just be a locally scoped one. So my thoughts are: it's not possible.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With