JavaScript Objects

In JavaScript, an object is a data structure that allows you to store collections of data, which are key-value pairs.


1. Creating Objects

There are two primary ways to create objects in JavaScript:

Using Object Literals

const person = {
    name: 'John',
    age: 30,
    greet: function() {
        console.log('Hello, ' + this.name);
    }
};

console.log(person.name); // Output: John
person.greet();           // Output: Hello, John

Try It Now

Explanation:

  • An object is created using curly braces {}. Inside, you can define properties (like name and age) and methods (like greet()).

Using the new Object() Syntax

const car = new Object();
car.make = 'Toyota';
car.model = 'Corolla';
car.year = 2022;

console.log(car.make);  // Output: Toyota

Try It Now

Explanation:

  • This approach creates an empty object and then assigns properties to it using dot notation.

2. Accessing Object Properties

You can access the properties of an object using either dot notation or bracket notation.

Dot Notation

console.log(person.name);  // Output: John

Try It Now

Bracket Notation

console.log(person['age']);  // Output: 30

Try It Now

Explanation:

  • Dot notation is simpler and used when you know the property name.
  • Bracket notation is useful when the property name contains special characters or is stored in a variable.

3. Modifying Object Properties

You can change an object’s properties by assigning new values to them:

person.age = 31;         // Modifies the age property
person['name'] = 'Jane'; // Modifies the name property

console.log(person.age);  // Output: 31
console.log(person.name); // Output: Jane

Try It Now

4. Adding New Properties to an Object

You can also add new properties to an existing object:

person.job = 'Developer';  // Adding a new property

console.log(person.job);   // Output: Developer

Try It Now

 

5. Deleting Object Properties

To remove a property from an object, you can use the delete keyword:

delete person.job;

console.log(person.job);   // Output: undefined

Try It Now

Note:

  • The delete operator removes a property from an object and returns true if successful.

6. Object Methods

Objects can have methods which are functions associated with the object. These methods can access and modify the properties of the object.

const calculator = {
    num1: 10,
    num2: 5,
    add: function() {
        return this.num1 + this.num2;
    },
    subtract: function() {
        return this.num1 - this.num2;
    }
};

console.log(calculator.add());      // Output: 15
console.log(calculator.subtract()); // Output: 5

Try It Now

Explanation:

  • The this keyword inside methods refers to the object itself, allowing access to its properties.

7. Object Constructor

You can also create objects using a constructor function.

function Car(make, model, year) {
    this.make = make;
    this.model = model;
    this.year = year;
}

const myCar = new Car('Honda', 'Civic', 2022);
console.log(myCar.make);  // Output: Honda

Try It Now

Explanation:

  • A constructor function is used to create multiple objects with similar properties.

8. The this Keyword in Objects

Inside an object method, this refers to the object itself.

const person = {
    name: 'Alice',
    greet: function() {
        console.log('Hello, ' + this.name);
    }
};

person.greet();  // Output: Hello, Alice

Try It Now

Explanation:

  • this in the method refers to the person object.

 

9. Iterating Over Object Properties

You can loop over the properties of an object using a for...in loop.

const person = {
    name: 'Bob',
    age: 25,
    job: 'Designer'
};

for (let key in person) {
    console.log(key + ': ' + person[key]);
}

Try It Now

Output:

name: Bob
age: 25
job: Designer

Explanation:

  • The for...in loop iterates over the keys of the object, allowing you to access both the key and the corresponding value.

10. Object.freeze() and Object.seal()

  • Object.freeze(): Prevents modification of object properties (makes the object immutable).
    const user = { name: 'Chris', age: 30 };
    Object.freeze(user);
    user.age = 35;  // Will not change
    console.log(user.age);  // Output: 30
    

    Try It Now

    Object.seal(): Prevents the addition or deletion of properties but allows modification of existing properties.

    const car = { make: 'Toyota', model: 'Corolla' };
    Object.seal(car);
    car.year = 2022;  // Will not be added
    car.make = 'Honda';  // Will be modified
    console.log(car);  // Output: { make: 'Honda', model: 'Corolla' }
    

    Try It Now

 

11. Object Destructuring

JavaScript allows extracting values from objects into variables using destructuring.

const person = { name: 'Sarah', age: 27 };

const { name, age } = person;
console.log(name);  // Output: Sarah
console.log(age);   // Output: 27

Try It Now

Explanation:

  • Destructuring allows you to unpack properties of the object into individual variables.

Summary

  • Objects are collections of key-value pairs in JavaScript.
  • Properties of objects can be accessed and modified using dot notation or bracket notation.
  • Objects can also contain methods that operate on their own properties.
  • JavaScript provides built-in methods like Object.freeze() and Object.seal() to control object mutability.
  • Object destructuring provides a convenient way to unpack values from objects.