lost9123193 lost9123193 -4 years ago 71
Javascript Question

Proper Way to Reference Variables in Javascript

I'm currently refactoring my code and I want to export an object array called

REFERENCE_LIST
to another file.

reference.js

export const REFERENCE_LIST = [
{name:"TypeA", foodList:foodAList},
{name:"TypeB", foodList:foodBList}
]

export const foodAList = ['apple', 'orange', 'banana']
];

export const foodBList = ['meat', 'fish']
];


However, the
foodList
field from
REFERENCE_LIST
is always "undefined". Am I referencing these arrays incorrectly?

Answer Source

You cannot reference variables in JS. You can reference object values, though - but those objects need to be created first for that:

export const foodAList = ['apple', 'orange', 'banana'];
export const foodBList = ['meat', 'fish'];

export const REFERENCE_LIST = [
  {name:"TypeA", foodList:foodAList}, 
  {name:"TypeB", foodList:foodBList}
];

You might also use getters where the order of creation doesn't matter:

export const REFERENCE_LIST = [
  {name:"TypeA", get foodList() { return foodAList; }}, 
  {name:"TypeB", get foodList() { return foodBList; }}
];

But even those will throw an exception when you evaluate them before the constants are initialised.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download