To create an object in JavaScript, you can use the object literal notation. This involves defining the object properties and their values within curly braces {}. For example:
1const person = {
2 name: 'John',
3 age: 30,
4 profession: 'Web Developer'
5};In this example, we have created an object person with three properties: name, age, and profession. Each property is assigned a value.
To modify an object, you can directly reassign the property values using dot notation or bracket notation. For example:
1person.name = 'Jane';In this case, we changed the name property value from 'John' to 'Jane'.
Another way to create objects is by using a function that returns an object. This is called a factory function. Here's an example:
1function createPerson(name, age, profession) {
2 return {
3 name,
4 age,
5 profession
6 };
7}
8
9const newPerson = createPerson('Alice', 25, 'Software Engineer');In this example, we defined a function createPerson that takes in name, age, and profession as parameters and returns an object with those properties.
You can call the createPerson function to create a new person object with the specified values.
Try running the code examples to see the output.
xxxxxxxxxx// Example 1const person = { name: 'John', age: 30, profession: 'Web Developer'};person.name = 'Jane';console.log(person);// Example 2function createPerson(name, age, profession) { return { name, age, profession };}const newPerson = createPerson('Alice', 25, 'Software Engineer');console.log(newPerson);


