In JavaScript, an object is a data structure that allows you to store collections of data and more complex entities. Objects are key-value pairs, where each key (also called a property) is associated with a value. The values can be of any data type, including other objects and functions.
Creating Objects
Object Literals
The most common way to create an object is by using an object literal:
let person = {
name: "John",
age: 30,
isStudent: false,
greet: function() {
console.log("Hello, my name is " + this.name);
}
};
Using the new Object() Syntax
Another way to create an object is by using the Object
constructor:
let person = new Object();
person.name = "John"
person.age = 30
person.isStudent = false
person.greet: function() {
console.log("Hello, my name is " + this.name);
}
Object of a class
We can also create object of a class and we have seen that example in our last session
class Person {
}
let person = new Person();
person.name = 'John';
person.age = 30;
console.log(person.name);
console.log(person.age)
Object of a function
We can also create object of a function because there was no concept of class in the earlier version of javascript. ES6 version of javascript introduced classes.
function person() {
}
let p = new person();
p.name = 'John';
p.age = 30;
console.log(p.name);
console.log(p.age)
Accessing Object
console.log(person)
Accessing Objects using Dot Notation
console.log(person.name)
console.log(person.age)
console.log(person.isStudent)
Accessing Objects using Bracket Notation
console.log(person["name"])
console.log(person["age"])
console.log(person["isStudent"])
Accessing a function inside an object
person.greet()
Accessing the keys, values and entries of an object
console.log(Object.keys(person))
console.log(Object.values(person))
console.log(Object.entries(person));
Modifying Properties
person.name = "Jack"
person["age"] = 31
Adding Properties
person.address = "123 Main Street"
Deleting Properties
delete person.isStudent;
for in loop
for (let key in person) {
console.log(key + ": " + person[key]);
}