4

The following code is working fine:

function a() { console.log("a"); };
function b() { console.log("b"); };

var F = {1:a,2:b};

F[1](); // log "a"
F[2](); // log "b"

but this one does not:

function a() { console.log("a"); };
function b() { console.log("b"); };

var A = 1;
var B = 2;
var F = {A:a,B:b};

F[A](); // log "TypeError : F[A] is not a function"

The idea is that A and B would be constant integer, used just for the sake of code readability. I know there are no "const" in javascript, but you get the idea.

What would be the clean way to get something like this work ? (I do not care that much if A and B are effectively constant or not at the end, just having them upper case indicates my future me not to change their value).

Vince
  • 3,979
  • 10
  • 41
  • 69

3 Answers3

15

In ES6, use computed property names:

{ [A]: a }
3

You're using A and B as identifiers in the JavaScript object you're creating, they aren't referencing the variables you've declared.

Instead you'll have to add them to the JavaScript object like so:

function a() { console.log("a"); };
function b() { console.log("b"); };

var A = 1;
var B = 2;
var F = {};
F[A] = a;
F[B] = b;

F[A]();
Aaron Powell
  • 24,927
  • 18
  • 98
  • 150
  • I am quite confused, thought my code and your code was totally equivalent ... My first batch of code in JavaScript comes with a lots of surprises – Vince Nov 18 '14 at 05:07
2

Within an object literal, all the "keys" are interpreted as strings, with or without quotes. So your key is "A", not 1. Your example is equivalent to var F = { "A": a, "B": b }.

Unfortunately, you simply cannot use a variable for a key within an object literal.

The only way to set a variable key is to use bracket notation:

F[A] = a;
Scott Rippey
  • 15,614
  • 5
  • 70
  • 85