DEV Community

Keerthana M
Keerthana M

Posted on

JS Object Constructors.

Constructors:

  1. The constructor in JavaScript is automatically called when the object is created.
  2. Constructor name should be start in the uppercase.
  3. Constructor is a initialization object specific value.
  4. It will reduce the repetition line of object creation.

Normal Object:

From the above code. the objects contains repeated variable in all objects we created. To reduce the code lines we can use Constructor object.

CONSTRUCTORS:

this refers to the current object(hp_01).
In the above code the function will call automatically once the object is created.

output:

1. Create:
To create an object or add properties to an existing object:
example:

const user = {
name: "John",
age: 30
};
user.email = "john@example.com"; //creating(adding)
console.log(user);

output:
{name: 'John', age: 30, email: 'john@example.com'}

2. Read:
To access properties of an object:
example:
const user = {
name: "John",
age: 30,
email: "john@example.com"
};

console.log(user.name); // Using Dot Notation
console.log(user["email"]); // Using Bracket Notation
console.log(name, age);

output:
John
john@example.com
John 30

3. Update:
To modify existing properties:
example:
const user = {
name: "John",
age: 30,
email: "john@example.com"
};
user.age = 35;
user["email"] = "john.doe@example.com"; //update
console.log(user);

output:
{name: 'John', age: 35, email: 'john.doe@example.com'}

4. Delete:
To remove properties from an object:
example:
const user = {
name: "John",
age: 30,
email: "john@example.com"
};
delete user.email; //delete
console.log(user);
output:
{name: 'John', age: 30}

Top comments (0)