Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I find out if an ES6 value is var / const / let after it is declared? [duplicate]

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.

like image 478
mikemaccana Avatar asked May 30 '19 10:05

mikemaccana


People also ask

Is var replaced by let?

let and const are block-scope variable declarations that can replace 'var' declarations in many cases.

Is const and let ES6?

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.


2 Answers

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');
}
like image 140
4 revs, 2 users 91% Avatar answered Sep 18 '22 21:09

4 revs, 2 users 91%


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.

like image 39
Ricardo Peres Avatar answered Sep 19 '22 21:09

Ricardo Peres