DEV Community

G Gokul
G Gokul

Posted on

OBJECTS IN JAVASCRIPT PART-2

CRUD operations in JS:

  • CRUD operations in JavaScript allow you to Create, Read, Update, and Delete data.
  • These operations are fundamental for managing data in applications.

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";
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"
};
// Using Dot Notation
console.log(user.name);
// Using Bracket Notation
console.log(user["email"]);
// Destructuring(TBD)
const { name, age } = user;
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";
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;
console.log(user);

output:
{name: 'John', age: 30}

CONSTRUCTORS:

  • In JavaScript, a constructor is a special function used to create and initialize objects.
  • It’s typically used with the new keyword to produce multiple objects of the same type.
  • constructor function names start with an uppercase letter.
  • this inside the constructor refers to that new current object.
  • This approach is useful when you need to create many objects with similar properties and methods.

example:
function Laptop(price,brand,storage,ram){
this. price = price;
this. brand = brand;
this. storage = storage;
this. ram = ram;
}
const hp01 = new Laptop(40000,"hp",512,8);
const lenovol1 = new Laptop(50000,"lenovo",1000,16);
const asusvivobook = new Laptop(48000,"asus",516,16);
const delld5 = new Laptop(45000,"dell",256,8);
console.log(hp01);
console.log(asusvivobook.ram);
console.log(lenovol1["price"])

output:
Laptop {price: 40000, brand: 'hp', storage: 512, ram: 8}
16
50000

Top comments (0)