DEV Community

vishwa v
vishwa v

Posted on

object(remaining topics)

JavaScript Properties
You can access object properties in these ways:

Dot notation
Bracket notation
Expression

Dot Notation

objectName.propertyName
person.firstname + " is " + person.age;
Enter fullscreen mode Exit fullscreen mode

Bracket Notation

objectName["propertyName"]
person["firstname"] + " is " + person["age"];
Enter fullscreen mode Exit fullscreen mode

In general, dot notation is preferred for readability and simplicity.

Bracket notation is necessary in some cases:

The property name is stored in a variable:
person[myVariable]

The property name is not a valid identifier:
person["last-name"]

Bracket notation is useful when the property name is stored in a variable:

let n1 = "firstName";
let n2 = "lastName";

let name = person[n2] + " " + person[n2];
Enter fullscreen mode Exit fullscreen mode

Constructor

It called automatically when object is created.

the name should be start with uppercase.

Initializing object specfic value.

THIS refer to current object

(.) is differentiate value and object

Example:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    <script>
        const hp=new Laptop(40000,"hp",512);
        const lenova=new Laptop(50000,"lenova",1000);
        const asus=new Laptop(30000,"asus",262);

        function Laptop(price,brand,storage){
            this.price=price;
            this.brand=brand;
            this.storage=storage;
        }
        console.log(lenova);
        console.log(hp);
        console.log(asus);
    </script>

</body>
</html>
Enter fullscreen mode Exit fullscreen mode

CRUD operations in JavaScript Objects

Create (Add new property)
You can create an object or add new properties to an existing object.

// Create object using literal
const student = { name: "Saran", age: 21 };

// Add new property
student.course = "Web Development";
console.log(student); 
// { name: "Saran", age: 21, course: "Web Development" }
Enter fullscreen mode Exit fullscreen mode

2. Read (Access property values)
You can read values using dot notation or bracket notation.

console.log(student.name);       // Dot notation → "Saran"
console.log(student["course"]);  // Bracket notation → "Web
Enter fullscreen mode Exit fullscreen mode

3. Update (Modify property values)
Update existing properties by reassigning values.

student.age = 22; 
student.course = "JavaScript"; 
console.log(student); 
// { name: "Saran", age: 22, course: "JavaScript" }
Enter fullscreen mode Exit fullscreen mode

4. Delete (Remove property)
Use the delete keyword to remove properties.

delete student.course;
console.log(student); 
// { name: "Saran", age: 22 }
Enter fullscreen mode Exit fullscreen mode

Top comments (0)