To create and work with objects in JavaScript, you can use the following steps:
const person = {
name: 'John',
age: 25,
greet: function() {
console.log('Hello!');
}
};
new
keyword along with the object constructor function. You can define the structure and behavior of the object using the constructor function.function Person(name, age) {
this.name = name;
this.age = age;
this.greet = function() {
console.log('Hello!');
}
}
const person = new Person('John', 25);
objectName.property
) or square bracket notation (objectName['property']
).console.log(person.name); // Output: John
console.log(person['age']); // Output: 25
person.age = 30;
person['name'] = 'Jane';
console.log(person.age); // Output: 30
console.log(person.name); // Output: Jane
person.sayHello = function() {
console.log('Hello, ' + this.name + '!');
};
person.sayHello(); // Output: Hello, Jane!
const { name, age } = person;
console.log(name); // Output: Jane
console.log(age); // Output: 30
this
Keyword: Inside an object's method, the this
keyword refers to the current object. It can be used to access and modify the object's properties.const person = {
name: 'John',
age: 25,
greet: function() {
console.log('Hello, ' + this.name + '!');
}
};
person.greet(); // Output: Hello, John!
These are some basic steps for creating and working with objects in JavaScript. Objects are versatile data structures and can be used in various ways to organize and manipulate data.