-5
const A = 0;
const LOOKUP = { A : "A"};
console.log(LOOKUP[A]);
console.log(LOOKUP[0]);

Result:

undefined
undefined

Second try:

var A = 0;
const LOOKUP = { A : "A"};
console.log(LOOKUP[A]);
console.log(LOOKUP[0]);

Result:

undefined
undefined

How am I supposed to do this then? And can somebody explain why this doesn't work in JavaScript the way one would expect it to work coming from other languages?

mroman
  • 1,354
  • 9
  • 14
  • I'm not sure what you're trying to do. If you want the object to be keyed by the value of the variable `A` (i.e. `0`), then create it like this: `{ [A] : "A"}`. If you want the object to be keyed be `"A"` (as it is now), then use `LOOKUP["A"]` or `LOOKUP.A` to access it. Also it has nothing to do with `const`/`var`. – FZs Oct 27 '22 at 05:19
  • Yeah nevermind, I made the assumptions that a const would be resolved within an object definition but thinking about it that wouldn't make sense. I haven't been coding for 4 years now so I was confused but it makes sense. So what I wanted is that LOOKUP has the key 0 (as A = 0) but obviously that's not how it can work. – mroman Oct 27 '22 at 05:21
  • Well, if you use `{ [A] : "A"}`, then either `const`s or `var`s or `let`s or even other expressions will be resolved, so even this is valid `{ [Math.floor(A + 1.5) - 1]: "A" }`. – FZs Oct 27 '22 at 05:26

5 Answers5

1

The correct way is:

const A = 0;
const LOOKUP = {};

LOOKUP[A] = 'A';

console.log(LOOKUP[A]);
console.log(LOOKUP[0]);
mroman
  • 1,354
  • 9
  • 14
0
const LOOKUP = { A : "A"};

The left side of the colon means that the key is the string "A". The string part is implicit, since all keys are strings (or symbols). So to access the property, you need to do console.log(LOOKUP.A) or console.log(LOOKUP["A"])

If you want the key to be a computed value, then you need to use square brackets:

const LOOKUP = { [A]: "A" };

That means that we should resolve the variable A, and use its value as the key. That key is the number 0, which then gets coerced into the string "0". You can then look it up by any of console.log(LOOKUP["0"]), console.log(LOOKUP[0]), or console.log(LOOKUP[A])

Nicholas Tower
  • 72,740
  • 7
  • 86
  • 98
0

Looks like you are searching for some enums (typescript):

enum ETest {
    A = 1
};

console.log(ETest['A']); // 1
console.log(ETest[1]); // A
Andrey Bessonov
  • 338
  • 1
  • 7
0

Doing LOOKUP[A] is like doing LOOKUP[0] which is undefined. You should try it as

console.log(LOOKUP["A"])
ehldev
  • 1
  • 1
0

This has nothing to do with const or var keyword. The way you are trying to access an object property is incorrect.

const A = 0;
const LOOKUP = { A : "A"};
console.log(LOOKUP["A"]); // Correct Approach: Property access through bracket notation should be done using a string (or a variable assigned to a string).
console.log(LOOKUP[0]); // Property `0` doesn't exist on object `LOOKUP`, so it'll return `undefined`.
Gourav Pokharkar
  • 1,568
  • 1
  • 11
  • 33