Search code examples
javascriptarraysstringglobal-variables

Get name of Variable a string in Javascript


lets say I have an array: it could look like this at one time:

var fruit = [apple,orange];

or like this:

var fruit = [orange, apple];

These are global variables, equaling some value - orange and apple How could I get the name of the variable at index 0 - (fruit[0]) of fruit as a string?

Thanks


Solution

  • To elaborate on @evolutionxbox comments – you'd need to use an object such as:

    const orange = 'An orange'
    const apple = 'An apple'
    
    const fruit = {
      orange,
      apple
    }
    
    console.log(Object.keys(fruit)) // [ 'orange', 'apple' ]
    console.log(Object.keys(fruit)[0]) // 'orange'
    console.log(fruit.apple) // 'An apple'