In this post we will see what are Objects in JavaScript? and how to create them.

Before looking at what are Objects in JavaScript, let us first look at what are objects in real world.

Consider what is a person in real word? A person is a thing that has some attributes as well as behaviors associated with it. For example, person’s name and age are attributes while how a person walks or talks are its behaviors. These attributes can also be called properties of the person. Similarly, the behavior can also be called methods.

So, in this example we have a Person that is an Object. That object has some properties like age and name plus it has behavior like walking.

Similar to real word, in JavaScript we have Objects. In fact everything is an Object is JavaScript. So how can you create a new Object such as Person in JavaScript?

There are multiple ways to create an object. The easiest is to use object lateral syntax:

var person = {age: 20, name: "Ali"}

Here we’ve created a person object which has two properties associated to it: age and name. Note that the properties are assigned through name, value pair i.e. name of property is age and its value is 20.

We can also associate methods or behaviors to our person object like this:

var person = {age: 20, name: "Ali", walk: function(){
   console.log('person is walking');}
}

How to access Properties and Methods of an Object?

So far, we have seen how to create an Object in JavaScript. But how do you access an object’s properties or methods? There are a couple of ways. One is to use the dot (.) syntax while the other is to use square brackets ([]):

console.log(person.age);
console.log(person['name']);

Similarly we can call the methods of an object:

person.walk();

Summary:

You need to be familiar with Objects in JavaScript and how to work with them if you want to enhance your JavaScript skills. The basics are explained in this post but there are many other things that you should learn also. That said, this post is meant to give a brief introduction to the Object Oriented world of JavaScript.

Leave a Reply

Your email address will not be published. Required fields are marked *