0

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?

2
  • yes the console is right because foodList was never declared or assigned so it remains undefined when you are trying to use it. Commented May 20, 2017 at 18:56
  • And the reason why the name field works is because it is a normal string. Commented May 20, 2017 at 18:58

1 Answer 1

3

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.