In this article, you will learn about JavaScript object in more details. All the previous examples have one or two objects created. Now we will look at more complex construct.
JavaScript objects are like arrays . You can access them like arrays using index. However, the index is its property.
For example:
let arr = [โjohnโ, โleeโ]; //an array
console.log(arr[0]); // prints the first element of array
Now consider an object.
let person = {
firstName : โJohnโ,
lastName: โMiroโ
};
//to access the property like array use the bracket notation
console.log(person[โfirstNameโ]);
How many ways to define the property?
How many ways to define the property?
Method 1: use double quotes
let person = {
โfirstNameโ: โJohnโ
};
Method 2: use single quotes
let person = {
โfirstNameโ: โJohnโ
};
Method 3: use no quotes
let person = {
firstName: โJohnโ
};
Nested Objects
Objects can contain other objects.
For example:
let person = {
firstName: โSherlockโ,
lastName: โHolmesโ,
address: {
street: โ221 Baker Streetโ,
city: โLondonโ,
country: โUKโ
}
};
How do you access the nested Object ?
The dot notation and the bracket notation still works for the nested objects.
console.log(person.address.street);
console.log(person.address[โcityโ]);
How to add or delete object property?
person.age = 34; /* simply type the object and its property name and it will add it.*/
delete person.address.city; /*will delete the city property in the nested object.*/
Objects Have Methods
Objects have methods that define the behavior of the object.
For example.
let person = {
firstName : โTedโ,
lastName: โcoddโ,
say: function (){
alert(โI am a data scientist!โ);
}
};
How to call the object function?
person.say();
The โthisโ keyword
You can refer to a property or method inside a function with โthisโ keyword.
let person = {
firstName : โTedโ,
lastName: โcoddโ,
talk: function (){
document.body.innerHTML = โMy name isโ + this.firstName;
}
};
In the next article, we will talk about strings.