3

Is there anyway to access ES6 constant by variable?

For ex.

const OPEN_TAB = 0;
const CLOSE_TAB = 1;

let action = 'OPEN';

console.log(window[`${action}_TAB`]); <-- something like that
Idan Gozlan
  • 3,173
  • 3
  • 30
  • 47

2 Answers2

9

No there is not (*). const declarations do not become properties of the global object.

You need to find another solution, such as creating an object and freeze it (to make it immutable):

const TAB = Object.freeze({
  OPEN: 0,
  CLOSE: 1,
});

console.log(TAB[action]);

I'd argue that relying on global variables (i.e. var) becoming properties of the global object is bad design anyway. If you want to look something up by name you really should have something like a map or a record (as shown above).


*: Well, you could use eval...

Felix Kling
  • 795,719
  • 175
  • 1,089
  • 1,143
0

For the current code you have, you can use eval (But take care!), it should be like this:

const OPEN_TAB = 0;
const CLOSE_TAB = 1;

let action = 'OPEN';

console.log( eval (action+'_TAB') );

The other way is to assume a new object to the const, then you can access the const easily like the common way you can access to JavaScript objects:

const TAB = {
OPEN:0,
CLOSE:1
};


let action = 'OPEN';


console.log(TAB[action]);
Community
  • 1
  • 1
Mohammad Kermani
  • 5,188
  • 7
  • 37
  • 61