Introduction to Objects

Objects store data and provide functions to manipulate the data. Here's an example of a goodStudent object.

var goodStudent = {
  name: "Mauricio",
  age: 19
}

name and age are called properties of the goodStudent object. The values of an object's properties can be accessed using dot notation:

goodStudent.name; // "Mauricio"
goodStudent.age; // 19

Dot notation can also be used to reassign properties to new values. Let's say yesterday was Mauricio's birthday. We can change his age to 20 like so:

goodStudent.age = 20;

Object properties aren't limited to strings and numbers. Properties can also be assigned to anonymous functions to give objects dynamic behavior.

var kid = {
  firstName: "Bart",
  lastName: "Simpson",
  fullName: function() {
    return(kid.firstName + " " + kid.lastName);
  }
}
kid.fullName(); // "Bart Simpson"

In the example above, the kid.firstName and kid.lastName syntax that we've seen previously is used to access the values associated with the firstName and lastName properties. The this keyword can also be used in an object function to refer to the current object. The following code is equivalent to the example above:

var kid = {
  firstName: "Bart",
  lastName: "Simpson",
  fullName: function() {
    return(this.firstName + " " + this.lastName);
  }
}
Question Click to View Answer

What does the following code print to the console?

var dog = {
  name: "fido",
  speak: "ruff"
}
console.log(dog.speak);

ruff

The dog variable is declared and assigned to an object with the name and speak properties. Dot notation is used to access the value associated with the speak property, and the value of the speak property ("ruff") is printed to the console.

What does the following code print to the console?

var cat = {
  name: "lala",
  sound: function() {
    return(this.name + " meow");
  }
}
console.log(cat.sound());

lala meow

The sound property is assigned to an anonymous function. The "this" keyword refers to the object that's assigned to the cat variable in this example.

What does the following code print to the console?

var joe = {
  weightKg: 70,
  heightMeters: 1.75,
  bodyMassIndex: function() {
    var r = this.weightKg / (this.heightMeters * this.heightMeters);
    return(r);
  }
}
console.log(joe.bodyMassIndex());

22.86 (approximately)

The joe variable is assigned to an object that has weightKg and heightMeters properties. The bodyMassIndex function is used to calculate the body mass index.

<-- Previous (And or Operators) Next (Math Object) -->