JavaScript

How to Create and Use JavaScript Objects


Objects are a fundamental data structure in JavaScript, allowing you to group related data and functions together. In this guide, we'll explore how to create and use JavaScript objects, and provide examples to illustrate their usage.

Creating Objects

You can create objects using object literals, which consist of key-value pairs:

const person = {
    firstName: `John`,
    lastName: `Doe`,
    age: 30,
    isStudent: false
};
    

Accessing Object Properties

You can access object properties using dot notation or bracket notation:

const firstName = person.firstName; // Dot notation
const lastName = person['lastName']; // Bracket notation
    

Modifying Object Properties

You can modify object properties by reassigning their values:

person.age = 31;
person['isStudent'] = true;
    

Adding and Deleting Properties

You can add new properties and delete existing ones:

person.city = `New York`; // Adding a property
delete person.isStudent; // Deleting a property
    

Objects with Methods

Objects can also contain methods, which are functions associated with the object:

const calculator = {
    add: function(a, b) {
        return a + b;
    },
    subtract: function(a, b) {
        return a - b;
    }
};
const result = calculator.add(5, 3); // Using a method
    

Object Constructors

You can create multiple objects with the same structure using constructors:

function Person(firstName, lastName) {
    this.firstName = firstName;
    this.lastName = lastName;
}
const person1 = new Person(`Alice`, `Johnson`);
const person2 = new Person(`Bob`, `Smith`);
    

Object Prototypes

Prototypes allow you to share properties and methods among objects of the same type:

Person.prototype.fullName = function() {
    return this.firstName + ' ' + this.lastName;
};
const fullName1 = person1.fullName();
const fullName2 = person2.fullName();
    

Conclusion

JavaScript objects are versatile data structures used for organizing and working with data and functions. By understanding how to create, access, modify, and use objects, you can build complex data structures and create reusable code in your JavaScript applications.

Happy coding!

Written by Surfside Media

Senior Full Stack Developer specializing in Web Technologies.