JavaScript Object Properties

Objects have properties, which are composed by a label associated with a value.

The value of a property can be of any type, which means that it can be an array, a function, and it can even be an object, as objects can nest other objects.

This is the object literal syntax we saw in the previous chapter:


const car = {};

We can define a colorproperty in this way:


let car = {
  color:"blue"
};

here we have a carwith a property named color, with the value blue.

Labels can be any string, but beware special characters: if I wanted to include a character not valid as a variable name in the property name, I would have had to use quotes around it:


let car = {
  color:"blue",
  "the color":"blue"
};

Invalid variable name characters include spaces, hyphens, and other special characters.

As you see, when we have multiple properties, we separate each property with a comma.

We can retrieve the value of a property using 2 different syntaxes.

The first is dot notation:


car.color//'blue'

The second (which is the only one we can use for properties with invalid names), is to use square brackets:


car["the color"]//'blue'

If you access an unexisting property, you'll get the undefinedvalue:


car.brand//undefined

Example


let car = {
  color:"blue",
  "the color":"blue"
};

console.log(car.color); // blue
console.log(car["the color"]); // blue
console.log(car.brand); // undefined

As said, objects can have nested objects as properties:


let car = {
  brand: {
    name:"Ford",
  },
  
  color:"blue",
};

In this example, you can access the brand name using


car.brand.name

Or


car["brand"]["name"]

Example


let car = {
  brand: {
    name:"Ford",
  },
  
  color:"blue",
};

console.log(car.brand.name);
console.log(car["brand"]["name"]);

You can set the value of a property when you define the object.

But you can always update it later on:


let car = {
  color:"blue",
};

car.color = "yellow"
car["color"] = "green"

Example


let car = {
  color:"blue",
};

car.color = "yellow"
car["color"] = "green"

console.log(car.color);

And you can also add new properties to an object:


car.model = "Toyota"
car.model = // 'Toyota' 

Example


let car = {
  color:"blue",
};

car.model = "Toyota"
console.log(car.model);

Given the object


let car = {
  color:"blue",
  brand:"Ford",
};

you can delete a property from this object using


delete car.brand 

Example


let car = {
  color:"blue",
  brand:"Ford",
};
delete car.brand 


console.log(car.color);
console.log(car.brand);

Let's see how object method is in the next chapter.