0
const persons = {
    name: 'David',
    age: 40
};

const myFunction = (x) => {
    console.log(persons.x)
};

myFunction('name');

If I pass myFunction('name'), I expect it to print 'David'.
If I pass myFunction('age'), I expect it to print 40.

But now it prints undefined. Anyone has any solutions ?

Dimisizz
  • 69
  • 9

1 Answers1

-1
const persons = {
    name: 'David',
    age: 40
};

const myFunction = (x) => {
    console.log(persons[x])
};

myFunction('name');

If you want to use a variable, you have to use the square bracket notation (object[property_name]) instead of the dot notation (object.property_name).

secan
  • 2,622
  • 1
  • 7
  • 24