Can arguments be passed into object properties?

I have completed this challenge and I am trying to understand what exactly is happening in my solution. Does 'carrot' get passed into this.name or does it just create a property called name (with a value of 'carrot') and adds it to the object? Also, in general, can arguments be passed into properties that are being created or accessed using dot or bracket notation?

  **Your code so far**

// Only change code below this line
class Vegetable {
constructor(name) {
  this.name = name;
}
}
// Only change code above this line

const carrot = new Vegetable('carrot');
console.log(carrot.name); // Should display 'carrot'
  **Your browser information:**

User Agent is: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/101.0.4951.67 Safari/537.36

Challenge: Use class Syntax to Define a Constructor Function

Link to the challenge:

const carrot = new Vegetable('carrot');
      ^this^                  ^name^

Think of Vegetable as just a template for an object that you can make when you call it with new. So Vegetable is very simple and is only making an object with the property name. If you made it without an argument it would still have made the property, but it would be undefined because you did not pass it a value.

this is basically a placeholder that will refer to an object, in this case carrot. And the string ‘carrot’ gets passed as an argument to the parameter name and is assigned to the property name as the value.

const carrot = {
name: 'carrot'
}

So that is basically what we end up with.

And you assign a value to both dot and bracket the same way you do everything, with the = operator and whatever value you want. Whether that value is stored as an argument/variable or a literal value like 10. You just use bracket if you are using variables to access the property, otherwise you can use dot if you know the names of the properties.

edit: And just to test it out because i was curious.

class Vegetable {

constructor(propertyName, name) {

  this[propertyName] = name;

}

}

const carrot = new Vegetable('food', 'carrot');

//console.log(carrot.name); // Should display 'carrot'

console.log(carrot)

you could pass a property name with bracket if you wanted.

Just for clarification, we can pass a property name with bracket notation but NOT dot notation?

It might help if you give a specific code example of what you are referring to?

Basically, if you are accessing a property using a variable then you have to use bracket notation:

const variable = 'name';
// Using a variable to access the property
console.log(carrot[variable]);
// Using the property name directly
console.log(carrot.name);

Both of the above console logs produce the same results, but the first one is using a variable for the property name and thus needs brackets.

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.