-3

I'm trying to learn javascript objects, starting with a very basic object and I cant get it to work. Can anyone tell me why the last console.log() comes back "undefined" instead of "Bill"??

const firstObject = {
 name: "Bill",
 profession: "Fireman",
 age: 30,
 getInfo: function (theInfo) {
  console.log(theInfo);
  console.log(this.name);
  console.log(this.theInfo);
 },
};
firstObject.getInfo("name");
Maheer Ali
  • 35,834
  • 5
  • 42
  • 73

2 Answers2

2

Use [] to access the property of object when key is a string. See Bracket Notation

const firstObject = {
 name: "Bill",
 profession: "Fireman",
 age: 30,
 getInfo: function (theInfo) {
  console.log(theInfo);
  console.log(this.name);
  console.log(this[theInfo]);
 },
};
firstObject.getInfo("name");
Maheer Ali
  • 35,834
  • 5
  • 42
  • 73
1

Your last console.log is logging a property not defined on your object since theInfo is not a property.

If you want to access a property using a variable, you have to use bracket notation, not dot notation:

const firstObject = {
 name: "Bill",
 profession: "Fireman",
 age: 30,
 getInfo: function (theInfo) {
  console.log(theInfo);
  console.log(this.name);
  console.log(this[theInfo]);
 },
};
firstObject.getInfo("name");
jo_va
  • 13,504
  • 3
  • 23
  • 47