Search code examples
javascriptconstantslet

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


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.


Solution

  • 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;
      let isConst = false;
      
      try {
        x = x;
      } catch (err) {
        isConst = true;
      }
      
      console.log(isConst ? 'const x' : 'let x');
    }
    
    {
      const x = 5;
      let isConst = false;
      
      try {
        x = x;
      } catch (err) {
        isConst = true;
      }
      
      console.log(isConst ? 'const x' : 'let x');
    }