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.