DEV Community

Chandru
Chandru

Posted on

JavaScript Objects: What I Learned

After learning strings and functions, the next topic I came across was objects.

An object is a way to keep related information together. Instead of creating separate variables for a person's name, age, and city, we can put them inside one object.

const person = {
  name: "John",
  age: 22
};
Enter fullscreen mode Exit fullscreen mode

Here, name and age are called properties.

We can access a property using a dot.

console.log(person.name);
Enter fullscreen mode Exit fullscreen mode

We can also change the value later.

person.age = 23;
Enter fullscreen mode Exit fullscreen mode

Objects can contain different types of data too. We can have strings, numbers, arrays, and even functions inside an object.

When a function is inside an object, we usually call it a method.

const person = {
  greet() {
    console.log("Hello!");
  }
};
Enter fullscreen mode Exit fullscreen mode

Then we can call it using person.greet().

Objects are used a lot in JavaScript. You'll see them when working with users, products, API responses, settings, and many other things.

The main thing I learned is that objects are a simple way to organize related data in one place.

At first, objects can feel a little confusing, but after using them in a few examples, they start to feel much more natural.

Top comments (0)