Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check that ES6 "variable" is constant?

Does anyone know some tricks how to do it? I tried to use try-catch:

"use strict";

const a = 20;

var isConst = false;
try {
   var temp = a; a = a+1; a = temp;
} catch (e) {
   isConst = true;
}

But unfortunately it works only in "strict" mode. Without "use strict" it perform all statements silently, without modification of a. Also I cannot wrap this code into some handy function (isConstant(someConst) for example) as any argument I'll pass to that function will be a new variable. So anyone know how to create isConstant() function?

like image 302
alexpods Avatar asked Apr 04 '15 18:04

alexpods


2 Answers

I don't think there is, but I also don't think this is a big issue. I think it might be useful to have the ability to know if a variable is const, and this exists in some other languages, but in reality since you (or someone on a team) will be defining these variables, you'd know the scope and the type of the variables. In other words, no you can't, but it's also not an issue.

The only case where it might be useful is if you could change the mutable property during runtime, and if changing this property had actual performance benefits; let, const, and var are treated roughly equally to the compiler, the only difference is that the compiler keeps track of const and will check assignments before it even compiles.

Another thing to note is that just like let, const is scoped to the current scope, so if you have something like this:

'use strict';

const a = 12;

// another scope
{
  const a = 13;
}

it's valid. Just be careful that it will look up in higher scopes if you don't explicitly state const a = 13 in that new scope, and it will give a Read Only or Assignment error:

'use strict';

const a = 12;

{
  a = 13; // will result in error
}
like image 200
josh Avatar answered Sep 25 '22 08:09

josh


Based on some of the answers here I wrote this code snippet (for client side JS) that will tell you how a "variable" was last declared--I hope it's useful.

Use the following to find out what x was last declared as (uncomment the declarations of x to test it):

// x = 0
// var x = 0
// let x = 0
// const x = 0

const varName = "x"    
console.log(`Declaration of ${varName} was...`)
try {
  eval(`${varName}`)
  try {
    eval(`var ${varName}`);
    console.log("... last made with var")
  } catch (error) {
    try {
      eval(`${varName} = ${varName}`)
      console.log("... last made with let")
    } catch (error) {
      console.log("... last made with const")
    }
  }
} catch (error) {
  console.log("... not found. Undeclared.")
}

Interestingly, declaring without var, let or const, i.e x = 0, results in var getting used by default. Also, function arguments are re-declared in the function scope using var.

like image 43
Rob Simpson Avatar answered Sep 23 '22 08:09

Rob Simpson