Object used to store multiple values in a single variable using key-value pairs.
const person = {
name : "Sherin",
age : 25,
role : "Software Tester"
};
console.log(person);
*OutPut *
`{name: 'Anees', age: 23, role: 'Software Tester'}`
Object Properties :
1.Dot Notation :
`console.log(person.name);
console.log(person.age);`
OutPut
`Sherin
25`
2.Bracket Notation :
`console.log(person["Role"]);`
OutPut
`Software Testing`
3.Add New Properties :
`person.country = "India";
console.log(person);`
*OutPut *
`{
name: "Sherin",
age: 23,
role: "Software Tester",
country: "India"
}`
4.Updating Properties :
`person.age = 24;
console.log(person.age);`
*OutPut *
`24`
5.Deleting Properties :
`delete person.role;
console.log(person);`
OutPut
`{
name: "Sherin",
age: 24,
country: "India"
}`
Object with Method
object can contain functions.
`const student = {
name: "Sherin",
greet() {
return `Hello, I'm ${this.name}`;
}
};
console.log(student.greet());`
OutPut
`Hello, I'm Sherin`
Nested Objects
Objects can contain other objects.
`const employee = {
name: "Sherin",
address: {
city: "Chennai",
pincode: 600001
}
};
console.log(employee.address.city);`
OutPut
`Chennai`
Object Methods
1.Object.keys()
Returns all keys.
`console.log(Object.keys(person));`
OutPut
`["name", "age", "country"]`
2.Object.values()
Returns all values.
`console.log(Object.values(person));`
OutPut
`["Sherin", 24, "India"]`
3.Object.entries()
Returns key-value pairs.
`console.log(Object.entries(person));`
OutPut
`[
["name", "Anees"],
["age", 24],
["country", "India"]
]`
Object Spread Operator
Merge the objects.
`const personal = {
name: "Sherin",
age: 25
};
const professional = {
role: "Software Tester",
country: "India"
};
const profile = {
...personal,
...professional
};
console.log(profile);`
OutPut
`{
name: "Sherin",
age: 23,
role: "Software Tester",
country: "India"
}`
Top comments (0)