Mark As Completed Discussion

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:

JAVASCRIPT
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:

JAVASCRIPT
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:

JAVASCRIPT
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.

JAVASCRIPT
OUTPUT
:001 > Cmd/Ctrl-Enter to run, Cmd/Ctrl-/ to comment