Object
An Object is a collection of key-value pairs. Each value is stored with a name called a key.It is collection of information in single variable.
Eg:
let student = {
name: "Pranay",
age: 21,
course: "ECE"
};
Accessing Object Values
There are two ways to access object properties.
1. Dot Notation
console.log(student.name);
console.log(student.age);
// Output:
Pranay
21
2. Bracket Notation
Bracket notation is useful when the property name is stored in a variable.
console.log(student["course"]);
// Output: ECE
Adding a New Property
We can add new properties anytime.
let student = {
name: "Pranay",
age: 21,
course: "ECE"
};
student.city = "Chennai";
console.log(student);
Updating a Property
We can change an existing value.
let student = {
name: "Pranay",
age: 21,
course: "ECE"
};
student.age = 22;
console.log(student.age);
Deleting a Property
Use the "delete" keyword to delete the object.
let student = {
name: "Pranay",
age: 21,
course: "ECE"
};
delete student.course;
console.log(student);
Core Components of Object
1. Properties: Variable Declaration
2. Methods: Function Declaration
let student = {
name: "Pranay",
greet: function () {
console.log("Hello!");
}
};
student.greet();
// Output: Hello!
This Keyword
Inside an object, this refers to the current object.
let student = {
name: "Pranay",
greet: function () {
console.log("Hello " + this.name);
}
};
student.greet();
// Output: Hello Pranay
Top comments (0)