About Lesson
Objects:
In JavaScript, objects are collections of key-value pairs. Each key is called a property, and the value associated with the key can be any data type, including functions (which are called methods when they belong to an object).
1. Creating Objects
You can create objects in JavaScript using two main approaches:
Object Literals
This is the most common and simplest way to create an object. You define the object directly using curly braces {}, where key-value pairs are written.
Example:
JavaScript
let person = {
name: "Manjeet",
age: 25,
greet: function() {
return "Hello, my name is " + this.name;
}
};
console.log(person.name); // Output: Manjeet
console.log(person.greet()); // Output: Hello, my name is Manjeet
In the example, person is an object with properties name, age, and a method greet.
Object Constructor
Another way to create an object is by using the Object() constructor or by creating a custom constructor function.
Example using Object():
JavaScript
let person = new Object();
person.name = "Manjeet";
person.age = 25;
person.greet = function() {
return "Hello, my name is " + this.name;
};
console.log(person.greet()); // Output: Hello, my name is Manjeet
Custom Constructor Function Example:
JavaScript
function Person(name, age) {
this.name = name;
this.age = age;
this.greet = function() {
return "Hello, my name is " + this.name;
};
}
let person1 = new Person("Manjeet", 25);
let person2 = new Person("Rakesh", 22);
console.log(person1.greet()); // Output: Hello, my name is Manjeet
console.log(person2.greet()); // Output: Hello, my name is Rakesh