Adding empty properties to an object

Based on some googling, I think I’m on the right track but, just want to confirm…

The prompt asks us to “Add a "bark" property to the object myDog and set it to a dog sound, such as “woof”.” So the solution is myDog.bark = "woof";

My question: if I were to just write myDog.bark; would that create an empty property in myDog? i.e., a property with no values assigned to it? I’m not sure why I would want to do that, I am just curious…

Your code so far


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

ourDog.bark = "bow-wow";

// Setup
var myDog = {
"name": "Happy Coder",
"legs": 4,
"tails": 1,
"friends": ["freeCodeCamp Campers"]
};

// Only change code below this line.
myDog.bark = "woof";

Your browser information:

User Agent is: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_13_4) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/79.0.3945.88 Safari/537.36.

Challenge: Add New Properties to a JavaScript Object

Link to the challenge:
https://www.freecodecamp.org/learn/javascript-algorithms-and-data-structures/basic-javascript/add-new-properties-to-a-javascript-object

Your code has been blurred out to avoid spoiling a full working solution for other campers who may not yet want to see a complete solution. In the future, if you post a full passing solution to a challenge and have questions about it, please surround it with [spoiler] and [/spoiler] tags on the line above and below your solution code.

Thank you.

Got it. Thanks for letting me know!

You can try:

// Only change code below this line.
myDog.favourites;
console.log(JSON.stringify(myDog)); // returns the original object

well, it doesn’t seem so…

1 Like

You could, but it would be hacky. It wouldn’t be that you’d simply do

myDog.bark;

that is a ‘getter’ for the property in question. You explicitly need to define a value, even if that value is no value at all. How would that work?

myDog.bark = undefined;

Boom. I’ve declared the property, it will be recognized by myDog.hasOwnProperty("bark"), but the value is… uninitialized. It’s an empty property.

There are edge cases where that might be useful - similar to the disabled attribute on HTML elements, where the existence of the property matters rather than its value. Fun thought experiment, though.

Cool! Thank you. So to add a property, it always has to be given some value, even if an undefined value. Thanks for explaining!

1 Like