1

How can I get a constant's value dynamically similar to constant() in PHP?

Below, I would like to access HELL_NO, but I have NO in a variable. Why does this return undefined?

const HELL_YES='warm';
const HELL_NO='cool';
var pick='NO';
console.log(window['HELL_'+pick]);
Jack Bashford
  • 43,180
  • 11
  • 50
  • 79
xam
  • 452
  • 2
  • 7
  • 15
  • 1
    `const`s do not get assigned to `window`, only `var`s on the top level do. You could also define your own object instead, `const obj = { HELL_YES: 'warm', HELL_NO: 'cool' };` then use bracket notation on obj, `obj['Hell_' + pick]` – CertainPerformance Mar 18 '19 at 22:37
  • @flppv Of course I did, I wouldn't have VTC'd otherwise – CertainPerformance Mar 18 '19 at 22:37
  • I used window as an example, for it didn't work and I don't know how else to make it work, so I asked the question. Thank you – xam Mar 18 '19 at 22:38
  • Well it's not the similar question, but I agree those answer contains answer to this question as well – flppv Mar 18 '19 at 22:39
  • I don't see how asking for the JavaScript equivalent to PHP's `constant()` is similar to asking about the difference between `let` and `var`. – John Coleman Mar 18 '19 at 22:39
  • Since you have a list of options based on `pick`, you can avoid `eval` by using conditions, for example in a `switch` statement. `switch (pick) { case "YES": console.log(HELL_YES); break; case "NO": console.log("HELL_NO"); break; default: console.log("unexpected value", pick); }` – ziggy wiggy Mar 18 '19 at 22:41
  • @JohnColeman There is no such thing as `constant()` in JS. The duplicates explain why `window['HELL_'+pick]` doesn't work. – Bergi Mar 18 '19 at 22:44

1 Answers1

2

You can use eval:

const HELL_YES='warm';
const HELL_NO='cool';
var pick='NO';
console.log(eval("HELL_" + pick));

EDIT

Because eval is evil, you should use an object instead:

const obj = {
  HELL_YES: "warm",
  HELL_NO: "cool"
};

console.log(obj["HELL_" + "YES"]);
Community
  • 1
  • 1
Jack Bashford
  • 43,180
  • 11
  • 50
  • 79