0

I am working on a pre-boot camp coding problem. I am passing in an object (ourDog) and a key (fiendly) into a function that creates a new property (key:value pair) and assigns a value of true to that key. Looking at the output, the property is added, but the key does not have the assigned value of 'friendly', it has the parameter name of key. I expected the key:value pair to (friendly: true). Here is the code.

var ourDog = {
  "name": "Camper",
  "legs": 4,
  "tails": 1,
  "friends": ["everything!"]
};


function addProperty(anObject, key) {

  anObject.key = true;

  return anObject;
};


var output = addProperty(ourDog, 'friendly');

console.log(output);
{name: "Camper", legs: 4, tails: 1, friends: Array(1), key: true}
  • change to `function addProperty(anObject, key) { anObject[key] = true; return anObject; };` – Sphinx Aug 04 '18 at 00:38
  • you are passing in a string, so you need to use `[]` bracket notation. It's kinda like you are writing `anyObject."friendly" = true` which obviously doesn't work – LegenJerry Aug 04 '18 at 00:40

1 Answers1

0

Change it from dot notation to brackets.

function addProperty(anObject, key) {

  anObject[key] = true;

  return anObject;
};

Dot notation is used to access an object's properties when the property is a valid JavaScript identifier. Since 'friendly' is a string, you need to use brackets.

Erik B
  • 329
  • 3
  • 11
  • It worked when I changed it from the dot notation to the bracket notation. Thank you! Now, I'll have to consider why that is. I am happy that change got it to work. – LittleShell Aug 04 '18 at 00:46
  • This is because `key` is a variable, when you do `anObject.key` you're saying grab the value with the key `'key'` (the string w/ value `'key'`), when you want to store a value in `'key'`, you either do `anObject.key = value` or `anObject['key'] = value`. However, you could also do `var foo = 'key'` and `anObject[foo] = value`, but if you did `anObject.foo = value` you're storing the `value` with the key `'foo'` – ACVM Aug 04 '18 at 00:52