Course Content
Data types and Values
0/1
Object-oriented programming in JavaScript
0/1
Error handling and debugging in JavaScript
0/1
JavaScript functions for string and array manipulation
0/1
JavaScript Libraries and Frameworks
0/1
JavaScript
About Lesson

JavaScript Objects Tutorial

Objects are a fundamental concept in JavaScript that allow you to group related data and functionality together. They are used to model real-world entities and their properties. Objects consist of key-value pairs, where each key is a property name and each value can be of any data type, including other objects.

The object type is a compound value where you can set properties (named locations) that each hold their own values of any type. This is perhaps one of the most useful value types in all of JavaScript.

Creating Objects

There are multiple ways to create objects in JavaScript:


  // Object Literal
  const person = {
      firstName: "John",
      lastName: "Doe",
      age: 30,
      isStudent: false
  };

  // Constructor Function 
  // Industries use this version most because they take the data object they 
  // read from the database and pass it to the function Person. 
  // The function then reads appropriate values and assigns 
  // them to the properties of the object dynamically
  function Person(firstName, lastName, age) {
      this.firstName = firstName;
      this.lastName = lastName;
      this.age = age;
  }

  const john = new Person("John", "Doe", 30);

  // ES6 Class
  class Person {
      constructor(firstName, lastName, age) {
          this.firstName = firstName;
          this.lastName = lastName;
          this.age = age;
      }
  }

  const jane = new Person("Jane", "Smith", 25);
  

Pictorially, here is the representation of the object in memory/behind the hood:

Accessing and Modifying Object Properties

You can access and modify object properties using dot notation or square brackets:


  console.log(person.firstName);     // John
console.log(person.lastName);        // Doe
console.log(person.age);             // 30
console.log(person.isStudent);       // false
console.log(person["firstName"]);    // John
console.log(person["lastName"]);     // Doe
console.log(person["age"]);          // 30
console.log(person["isStudent"]);    // false
  console.log(john["lastName"]);     // Doe
  console.log(john["age"]);          // 30


  person.age = 31;
  john["age"] = 31;

Note: Perperties can be assessed with dot notation and bracket notation, 
but dot notation is shorter and hence is the most preferred method.
Bracket notations are useful when the property being assessed 
has special characters in it. eg: person["john doe!"]
  

Adding and Deleting Properties

You can add new properties to an object and delete existing ones:


  person.nationality = "American";
  delete john.age;
  

Object Methods

Objects can also contain functions, known as methods, to perform actions:


  const calculator = {
      add: function(a, b) {
          return a + b;
      },
      subtract: function(a, b) {
          return a - b;
      }
  };

  console.log(calculator.add(5, 3)); // 8

//Extending the person object to add functions
const person = {
    firstName: "John",
    lastName: "Doe",
    age: 30,
    isStudent: false,
    getFullName: function() {
        return `${this.firstName} ${this.lastName}`;
    },
    greet: function() {
        if (this.isStudent) {
            return `Hello, I'm ${this.getFullName()}, and I'm a student.`;
        } else {
            return `Hello, I'm ${this.getFullName()}.`;
        }
    },
    celebrateBirthday: function() {
        this.age++;
        return `Happy birthday! Now I'm ${this.age} years old.`;
    }
};

console.log(person.getFullName()); // John Doe
console.log(person.greet()); // Hello, I'm John Doe.
console.log(person.celebrateBirthday()); // Happy birthday! Now I'm 31 years old.
  

Nested Objects

Objects can contain other objects as properties, creating a hierarchical structure:


  const car = {
      make: "Toyota",
      model: "Camry",
      year: 2022,
      owner: {
          firstName: "Alice",
          lastName: "Johnson"
      }
  };

  console.log(car.owner.firstName);    // Alice
  

Iterating Through Object Properties

You can loop through object properties using for...in loops:


  for (const key in person) {
      console.log(`${key}: ${person[key]}`);
  }
  

Object Destructuring

Destructuring allows you to extract properties from an object into individual variables:


  const { firstName, lastName } = person;
  console.log(firstName);      // John