DEV Community

Owais Khan
Owais Khan

Posted on • Updated on

Objects in JavaScript

Object in javascript is data structure used to hold key value pairs.
E.g; If we have data about book and we want to store it in a way so that we can access it easily. For that we can create object like below:

let book = {
  name: "Harry Potter",
  author: "JK Rowling"
}
Enter fullscreen mode Exit fullscreen mode

Here I created an object book with two properties name and author. Properties in objects are like variables to which we assign values. In above example nameand author are keys and "Harry Potter" and "JK Rowling" are values respectively.

To access the properties of object we can use one of two methods:

  1. Dot Operator.
  2. Bracket syntax.

To access with dot operator we just have to write:

book.name // Harry Potter
Enter fullscreen mode Exit fullscreen mode

with bracket syntax:

book["name"] // Harry Potter
Enter fullscreen mode Exit fullscreen mode

In case of dot operator it is important to note that properties should be declared in the same way as variable which means properties should start with letters or underscore and not with numbers or special characters.

let x = {
  1name: "john" // cannot be accessed with dot operator
}
console.log(x.1name); // throws error
Enter fullscreen mode Exit fullscreen mode

But in bracket syntax we can do something like this:

let x = {
  "1name": "john" 
}
console.log(x["1name"]); // john
Enter fullscreen mode Exit fullscreen mode

We can also define methods in objects. Functions inside object are known as Methods. If we have define a method inside our book object:

let book = {
  name: "Harry Potter",
  author: "JK Rowling",
  sayHi: function(){
   console.log("Hi...")
 }
}
Enter fullscreen mode Exit fullscreen mode

In above example we created sayHi method. We can access this method like:

book.sayHi(); // Hi...
Enter fullscreen mode Exit fullscreen mode

Other handy way of defining methods inside objects:

let book = {
  name: "Harry Potter",
  author: "JK Rowling",
  sayHi(){
   console.log("Hi...")
 }
}
Enter fullscreen mode Exit fullscreen mode

Now, this method looks better.

If we want to access object properties inside object methods, we can access them with thiskeyword. In objects this keyword refers to that object in which that method resides.
E.g:

let book = {
  name: "Harry Potter",
  author: "JK Rowling",
  sayHi(){
   console.log(`${this.name} is written by ${this.author}.`)
 }
}
sayHi(); // Harry Potter is written by JK Rowling.
Enter fullscreen mode Exit fullscreen mode

In above example this keyword refer to book object. So, this.name is like saying book.name.

Top comments (0)