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"
}
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 name
and 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:
- Dot Operator.
- Bracket syntax.
To access with dot operator we just have to write:
book.name // Harry Potter
with bracket syntax:
book["name"] // Harry Potter
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
But in bracket syntax we can do something like this:
let x = {
"1name": "john"
}
console.log(x["1name"]); // john
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...")
}
}
In above example we created sayHi
method. We can access this method like:
book.sayHi(); // Hi...
Other handy way of defining methods inside objects:
let book = {
name: "Harry Potter",
author: "JK Rowling",
sayHi(){
console.log("Hi...")
}
}
Now, this method looks better.
If we want to access object properties inside object methods, we can access them with this
keyword. 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.
In above example this
keyword refer to book
object. So, this.name
is like saying book.name
.
Top comments (0)