#  Objects In JavaScript

# what is object

in JS, object is a data structure used to store related information together using `key-value` pair

Each piece of data inside an object has:

*   a **key** (also called a property name)
    
*   a **value** (the actual data stored)
    

The key helps us identify the value.

Example:

```plaintext
const person = {
  name: "Dushyant",
  age: 21,
  city: "Jhansi"
};
```

In this object:

```plaintext
name → key
"Dushyant" → value

age → key
21 → value

city → key
"Panna" → value
```

So the object is simply **a structured way to store related data in one place**.

* * *

### why do we need object

Example without objects:

```plaintext
const name = "Dushyant";
const age = 21;
const city = "Panna";
```

Now imagine a program storing **100 students**.

Managing separate variables becomes messy very quickly.

Objects solve this problem by **grouping related data together**.

Example using an object:

```plaintext
const student = {
  name: "Dushyant",
  age: 21,
  course: "Web Development"
};
```

Now everything about the student is stored inside **one structure**.

* * *

### How JavaScript Stores Objects

An object is written using **curly braces** `{}`.

Inside the braces we define **properties** using this format:

```plaintext
key : value
```

Example:

```plaintext
const car = {
  brand: "Tesla",
  model: "Model 3",
  year: 2024
};
```

Here:

```plaintext
brand → key
"Tesla" → value
```

* * *

# way to create object

there are mainly 3 way to create a object -

1.  Object Literal (most common)
    

Syntax

```plaintext
const objectName = {
  key1: value1,
  key2: value2
};
```

### Example

```plaintext
const person = {
  name: "Dushyant",
  age: 21,
  city: "Panna"
};
console.log(person);
```

we use this method **most of the time** because it is short and readable.

### 2\. Object Constructor

JavaScript provides a built-in **Object constructor**.

### Syntax

```plaintext
const objectName = new Object();
objectName.key = value;
```

### Example

```plaintext
const person = new Object();

person.name = "Dushyant";
person.age = 21;
person.city = "Panna";
console.log(person);
```

This works, but it is **less common** compared to object literal.

### 3\. Constructor Function

first of all why do we need this I, f you create objects like this again and again:

```plaintext
const student1 = {
  name: "Dushyant",
  age: 21,
  course: "Web Dev"
};

const student2 = {
  name: "Rahul",
  age: 22,
  course: "Web Dev"
};
```

You are **repeating the same structure** every time.  
That’s bad design and becomes messy when you have **10, 50, or 100 students**.

A **constructor function** solves this by acting like a **blueprint** for creating objects

so a construcctor duction is a special function used to reaate multiple object with the same structure

instead of writting the object again and again , you define the structure once, then creeate many object from it

### syntax:

```plaintext
function ConstructorName(parameter1, parameter2) { // 
  this.property1 = parameter1;
  this.property2 = parameter2;
}

const obj = new ConstructorName(value1, value2);
```

### Example

```plaintext
function Student(name, age, course) {
  this.name = name;
  this.age = age;
  this.course = course;
}


const student1 = new Student("Dushyant", 21, "Web Development");
console.log(student1);
```

*   `Student` is the name of the constructor.
    
*   `name`, `age`, and `course` are **parameters** that will receive values when we create a new object.
    
*   `this` refers to the **new object being created**.
    
*   `this.name` creates a property called `name` inside the object.
    
*   `name` is the value passed when the object is created.
    

So the value of `name` gets stored in the object's `name` property.

*   `new` tells JavaScript to create a new object.
    
*   `"Dushyant"`, `21`, and `"Web Development"` are passed as values.
    

* * *

# accessing object properties

in JS we can access the value stored in an object using two method

1.  ### Dot notation
    
2.  ### Bracket notation
    

## Dot notation

it is the most common and simplest way to access object properties.

### Syntax

```plaintext
objectName.propertyName
```

### Example

```plaintext
const person = {
  name: "Dushyant",
  age: 21,
  city: "Panna"
};

console.log(person.name);
console.log(person.age);
```

### Output

```plaintext
Dushyant
21
```

### Explanation

Here:

```plaintext
person.name
```

*   `person` → object
    
*   `name` → property
    

The dot (`.`) is used to access the value stored in that property.

## Bracket Notation

Bracket notation is another way to access object properties.

### Syntax

```plaintext
objectName["propertyName"]
```

### Example

```plaintext
const person = {
  name: "Dushyant",
  age: 21
};

const key = "name";

console.log(person[key]);
```

Output

```plaintext
Dushyant
```

Here JavaScript reads the value of `key` and accesses the property.

since we have already have dot why do we actually required bracket notation because bracket notation is usefull when the property named is stored in a variable

### Dynamic Case (Dot Fails)

```plaintext
const person = {
  name: "Dushyant",
  age: 21
};

const key = "name";

console.log(person.key);
```

Output:

```plaintext
undefined
```

Because JavaScript looks for a property literally called `"key"`.

Your object is:

```plaintext
{
 name: "Dushyant",
 age: 21
}
```

There is **no property named** `"key"`.

* * *

### Bracket Notation Solves This

```plaintext
const person = {
  name: "Dushyant",
  age: 21
};

const key = "name";

console.log(person[key]);
```

Output:

```plaintext
Dushyant
```

Why this works:

```plaintext
person[key]
```

JavaScript replaces `key` with `"name"`.

So it becomes:

```plaintext
person["name"]
```

And then it returns the value.

another eg

### Trying with Dot Notation (Fails)

```plaintext
const student = {
  "first name": "Dushyant",
  age: 21
};

console.log(student.first name);
```

This will **cause an error**.

Why?

Because JavaScript reads it like this:

```plaintext
student.first
name
```

It thinks:

*   access property `first`
    
*   then sees `name` as a separate word
    

So the syntax becomes **invalid**.

* * *

# Correct Way Using Bracket Notation

```plaintext
const student = {
  "first name": "Dushyant",
  age: 21
};

console.log(student["first name"]);
```

Output:

```plaintext
Dushyant
```

### Golden rule

Use **dot notation** when property names are simple:

```plaintext
student.age
```

Use **bracket notation** when property names contain **spaces or special characters**:

```plaintext
student["first name"]
```

Bracket notation treats the property as a **string**:

```plaintext
student["first name"]
```

JavaScript directly looks for the property `"first name"` inside the object.

* * *

# Adding, Updating, and Deleting Object Properties in JavaScript

Objects in JavaScript are **mutable**, which means you can **change them after creation**.  
You can **add**, **update**, or **delete** properties anytime.

* * *

## 1\. Adding Properties

You can add a new property using **dot notation** or **bracket notation**.

### dot notation

```plaintext
const person = {
  name: "Dushyant",
  age: 21
};

// Add new property
person.city = "Panna";

console.log(person);
```

**Output:**

```plaintext
{ name: 'Dushyant', age: 21, city: 'Panna' }
```

### bracket notation

Useful if the property name has spaces or is dynamic:

```plaintext
person["country"] = "India";

console.log(person);
```

**Output:**

```plaintext
{ name: 'Dushyant', age: 21, city: 'Panna', country: 'India' 
```

## 2\. Updating Properties

if a value already exist , you can update its value

```plaintext
const person = {
  name: "Dushyant",
  age: 21,
  city: "Jhansi

};
person.age = 22;
person["city"] = "Bhopal";

console.log(person);
```

**Output:**

```plaintext
{ name: 'Dushyant', age: 22, city: 'Bhopal', country: 'India' }
```

*   Dot or bracket works for updating too.
    
*   JavaScript **overwrites the old value**.
    

## 3 . Deleting Properties

To remove a property, use the `delete` **keyword**.

```plaintext
delete person.country;

console.log(person);
```

**Output:**

```plaintext
{ name: 'Dushyant', age: 22, city: 'Bhopal' }
```

*   `delete` removes the property completely.
    
*   Accessing it afterward will give `undefined`.
    

## Key Points to remeber

1.  Objects are **dynamic** – you can add or remove properties anytime.
    
2.  Dot notation is easier for **simple property names**.
    
3.  Bracket notation is needed for **spaces or dynamic property names**.
    
4.  Updating a property simply **overwrites the old value**.
    
5.  Deleting removes the property completely from the object
    

* * *

# Objet Built-in method

(adance topic if you want you can skip it )

JavaScript provides several **built-in methods** to work with objects. These methods help you **read keys, values, entries, or freeze/merge objects**.

We’ll cover the **main ones beginners should know**.

* * *

## 1\. `Object.keys()`

*   Returns an **array of all keys** in an object.
    

### Example

```plaintext
const person = {
  name: "Dushyant",
  age: 21,
  city: "Panna"
};

console.log(Object.keys(person));
```

**Output:**

```plaintext
["name", "age", "city"]
```

* * *

## 2\. `Object.values()`

*   Returns an **array of all values** in an object.
    

### Example

```plaintext
console.log(Object.values(person));
```

**Output:**

```plaintext
["Dushyant", 21, "Panna"]
```

* * *

## 3\. `Object.entries()`

*   Returns an **array of key-value pairs** as arrays.
    

### Example

```plaintext
const person = {
  name: "Dushyant",
  age: 21,
  city: "Panna"
};

const entries = Object.entries(person);

console.log(entries);
```

**Output:**

```plaintext
[
  ["name", "Dushyant"],
  ["age", 21],
  ["city", "Panna"]
]
```

*   Useful for **looping through objects** with `for...of`.
    

* * *

## 4\. `Object.assign()`

*   Copies properties from **one or more objects** to a target object.
    
*   the target object is mpdified
    

### Syntax

```plaintext
Object.assign(targetObject, sourceObject1, sourceObject2, ...);
```

*   `targetObject` → the object you want to modify.
    
*   `sourceObject1, sourceObject2` → objects whose properties will be copied.
    

### Example

```plaintext
const obj1 = { name: "Dushyant", age: 21 };
const obj2 = { city: "Panna", country: "India" };

const merged = Object.assign({}, obj1, obj2);

console.log(merged);
```

**Output:**

```plaintext
{ name: "Dushyant", age: 21, city: "Panna", country: "India" }
```

*   Good for **merging objects**.
    

* * *

## 5\. `Object.freeze()`

*   Makes an object **immutable** (cannot add, delete, or update properties).
    

### Example

```plaintext
const person = { name: "Dushyant", age: 21 };
Object.freeze(person);

person.age = 22; // This will not work
person.city = "Panna"; // This will not work

console.log(person);
```

**Output:**

```plaintext
{ name: "Dushyant", age: 21 }
```

> Use `Object.freeze()` only if you want to **protect an object from changes**.

* * *

## Key Notes for Your Blog

1.  `Object.keys(obj)` → gets all **property names**.
    
2.  `Object.values(obj)` → gets all **property values**.
    
3.  `Object.entries(obj)` → gets all **key-value pairs** as arrays.
    
4.  `Object.assign(target, ...sources)` → **merge objects**.
    
5.  `Object.freeze(obj)` → **prevents modifications**.
    

* * *

# Looping through object

1.  `for...in` Loop
    

it is the loop is used to go through all properties (keys) of an objjecct one by one.

### Basic Syntax

```plaintext
for (let key in object) {
  // code using key
}
```

*   `key` → variable that holds the property name (like `"name"` or `"age"`) in each iteration
    
*   `object` → the object you want to loop through
    

### Example

```plaintext
const person = {
  name: "Dushyant",
  age: 21,
  city: "Panna"
};

for (let key in person) {
  console.log(key, ":", person[key]);
}
```

**Output:**

```plaintext
name : Dushyant
age : 21
city : Panna
```

*   `for (let key in person)`
    
    *   Starts the loop.
        
    *   On the first iteration, `key = "name"`
        
    *   Second iteration, `key = "age"`
        
    *   Third iteration, `key = "city"`
        
*   `console.log(key, ":", person[key])`
    
    *   Accesses the value of each property using **bracket notation**.
        
    *   Dot notation won’t work here because `key` is a variable, not a literal property name.
        

### Things You Must Know About `for...in`

1.  **Includes inherited properties**
    

```plaintext
const parent = { parentProp: "Parent" };
const child = Object.create(parent);
child.name = "Dushyant";

for (let key in child) {
  console.log(key);
}
```

**Output:**

```plaintext
name
parentProp
```

*   `for...in` will also loop through properties inherited from the prototype.
    
*   If you want **only own properties**, you should check with `hasOwnProperty()`:
    

```plaintext
for (let key in child) {
  if (child.hasOwnProperty(key)) {
    console.log(key);
  }
}
```

Output:

```plaintext
name
```

2.  **Order is not guaranteed**
    

*   In some cases, especially with numeric keys, the order may not be exactly as you defined.
    
*   Don’t rely on `for...in` for ordered output.
    

3.  **Best for simple objects**
    

*   For large objects or functional style code, `Object.keys()` or `Object.entries()` + `forEach` / `for...of` is preferred.
    

## 2\. Using `Object.keys()` + `forEach()`

You can first get **all keys** using `Object.keys()` and then loop through them.

### Example

```plaintext
Object.keys(person).forEach(key => {
  console.log(key, ":", person[key]);
});
```

**Output:**

```plaintext
name : Dushyant
age : 21
city : Panna
```

**Explanation:**

*   `Object.keys(person)` returns an array of keys: `["name", "age", "city"]`.
    
*   `.forEach()` loops through this array.
    
*   You can access values dynamically with `person[key]`.
    

## 3\. Using `Object.entries()` + `for...of`

`Object.entries()` returns an array of **\[key, value\] pairs**, which makes looping very clean.

### Example

```plaintext
for (const [key, value] of Object.entries(person)) {
  console.log(key, ":", value);
}
```

**Output:**

```plaintext
name : Dushyant
age : 21
city : Panna
```

**Explanation:**

*   `Object.entries(person)` gives `[["name","Dushyant"], ["age",21], ["city","Panna"]]`.
    
*   `[key, value]` uses **array destructuring** to directly get each key and value.
    

Summary Table

| Method | Example | Notes |
| --- | --- | --- |
| `for...in` | `for (let key in obj)` | Simple, beginner-friendly |
| `Object.keys()` | `Object.keys(obj).forEach(...)` | Works well with arrow functions or functional style |
| `Object.entries()` | `for (const [key,value] of Object.entries(obj))` | Cleanest when you need both keys & values |

* * *

# Object Destructing

**Objecct destructing lets you extract properties from an object intoo variables in one line**

* * *

### Syntax

```plaintext
const { property1, property2 } = object;
```

*   `property1` and `property2` become **variables** containing the values from the object.
    

* * *

### Example

```plaintext
const person = {
  name: "Dushyant",
  age: 21,
  city: "Panna"
};

// Destructuring
const { name, age } = person;

console.log(name); // Dushyant
console.log(age);  // 21
```

**Explanation:**

*   Instead of writing:
    

```plaintext
const name = person.name;
const age = person.age;
```

*   You can get both in **one line** using destructuring.
    

* * *

### Another Example With Renaming

```plaintext
const { name: firstName, city: hometown } = person;

console.log(firstName); // Dushyant
console.log(hometown);  // Panna
```

*   `name: firstName` → creates a variable `firstName` from `person.name`.
    

* * *

### Why It’s Useful

1.  Makes code **cleaner** and shorter.
    
2.  Easy to **access multiple properties** at once.
    
3.  Works well in **function parameters**, e.g.:
    

```plaintext
function printPerson({ name, age }) {
  console.log(name, age);
}

printPerson(person); // Dushyant 21
```

* * *

# Object Spread Operator

Tthe object spread operator`(...)` basically let you copy all properties from one object into another quickly.

it is similar to `Object.assign( )` but shorter and cleaner

### Syntax

```plaintext
const newObject = { ...oldObject };
```

*   `...oldObject` → takes all properties of `oldObject` and **spreads them into** `newObject`.
    

### Example 1: Copying an Object

```plaintext
const person = {
  name: "Dushyant",
  age: 21
};

const copyPerson = { ...person };

console.log(copyPerson);
```

**Output:**

```plaintext
{ name: "Dushyant", age: 21 }
```

*   `copyPerson` is now a **separate object** with the same properties
    

### Example 2: Adding New Properties While Copying

```plaintext
const updatedPerson = { ...person, city: "Panna" };

console.log(updatedPerson);
```

**Output:**

```plaintext
{ name: "Dushyant", age: 21, city: "Panna" }
```

*   You can **add or override properties** while copying.
    
*   If the property already exists, the **last value wins**:
    

```plaintext
const updatedPerson2 = { ...person, age: 22 };
console.log(updatedPerson2);
```

Output:

```plaintext
{ name: "Dushyant", age: 22 }
```

* * *

# object freezing and sealing

<mark class="bg-yellow-200 dark:bg-yellow-500/30">imp topic for interview prep</mark>

Alright, let’s explain **Object Freezing and Sealing** in the simplest, beginner-friendly way.

JavaScript gives you ways to **control whether objects can be changed**:

1.  `Object.freeze()` → completely prevents changes.
    
2.  `Object.seal()` → allows changing existing properties but **prevents adding or deleting** properties.
    

* * *

## 1\. `Object.freeze()`

**as its name suggest freezing an objecct you can not add, remove or change its properties. the objecct become immutable.**

### Example

```plaintext
const person = { name: "Dushyant", age: 21 };

Object.freeze(person);

person.age = 22;       //  does NOT work
person.city = "Panna"; //  does NOT work
delete person.name;    //  does NOT work

console.log(person);
```

**Output:**

```plaintext
{ name: "Dushyant", age: 21 }
```

*   Everything stays **exactly the same**.
    
*   Useful when you want to **protect an object from accidental changes**.
    

* * *

## 2\. `Object.seal()`

as its name suggest sealing an object means you cannot add or delete properties , but you can update existing one

### Example

```plaintext
const person = { name: "Dushyant", age: 21 };

Object.seal(person);

person.age = 22;       //  works
person.city = "Panna"; //  does NOT work
delete person.name;    //  does NOT work

console.log(person);
```

**Output:**

```plaintext
{ name: "Dushyant", age: 22 }
```

*   Existing properties can be **updated**.
    
*   New properties cannot be **added**, and existing ones cannot be **removed**.
    

* * *

### Quick Summary Table

| Method | Add Properties | Update Properties | Delete Properties |
| --- | --- | --- | --- |
| `Object.freeze` | No | No | No |
| `Object.seal` | No | Yes | No |

* * *

### Why They Matters

*   Use `freeze()` for objects that must **never change**, like constants.
    
*   Use `seal()` when you want to **allow updates but prevent structure changes**.
    

* * *
