Understanding and Using Objects in JavaScript

Posted on Jan 28, 2023

JavaScript is an object-oriented programming language, which means that it uses objects to represent and manipulate data. In this post, we’ll take a closer look at what objects are in JavaScript and how to use them.

What are Objects in JavaScript?

In JavaScript, an object is a collection of properties and methods. A property is a piece of data that is associated with an object, and a method is a function that can be used to perform actions on an object.

Here’s an example of a simple object:

let person = {
    name: "John Smith",
    age: 30,
    greet: function() {
        console.log("Hello, my name is " + this.name);
    }
}

In this example, the person object has three properties: name, age, and greet. The name and age properties are strings and numbers, respectively, and the greet method is a function that logs a greeting to the console.

Creating Objects

There are several ways to create objects in JavaScript. One way is to use object literals, like in the example above. Another way is to use the Object constructor:

let person = new Object();
person.name = "John Smith";
person.age = 30;
person.greet = function() {
    console.log("Hello, my name is " + this.name);
}

Another way to create objects is by using classes, which are a blueprint for creating objects.

class Person {
    constructor(name, age) {
        this.name = name;
        this.age = age;
    }
    greet() {
        console.log("Hello, my name is " + this.name);
    }
}
let person = new Person("John Smith", 30);

Accessing and Modifying Object Properties

You can access and modify object properties using the dot notation or the bracket notation. The dot notation is used when the property name is a valid identifier, and the bracket notation is used when the property name is a string or an expression.

let person = { name: "John Smith", age: 30 };
console.log(person.name); // "John Smith"
console.log(person["age"]); // 30

person.name = "Jane Doe";
person["age"] = 35;

Using Object Methods

You can use object methods by calling them on an object using the dot notation or the bracket notation.

let person = { 
    name: "John Smith",
    age: 30,
    greet: function() {
        console.log("Hello, my name is " + this.name);
    }
};
person.greet(); // "Hello, my name is John Smith"

In this post we have covered the basics of JavaScript objects, including what they are, how to create them, how to access and modify object properties, and how to use object methods. With this knowledge, you will be able to create your own objects and use them to represent and manipulate data in your JavaScript programs.