# Understanding Objects in JavaScript

Think of an object like a filled-in form. A job application form has labelled fields: Name, Age, City, Qualification. Each label is the KEY and what we write in the field is the VALUE. A JavaScript object works exactly the same way.

## What are objects and why do we need them?

Imagine, we want to store information about a person, their name, age and city. WIthout objects we might need separate variables:

```javascript
let name = 'Alice';
let age  = 25;
let city = 'Mumbai';
```

This works for one person, but what about 100 people? We might need 300 variables for these 100 people. Objects solve this by letting is group all related data under one name:

```javascript
const person = {
  name: 'Alice',
  age:  25,
  city: 'Mumbai',
};
```

Now, everything about person lives in one container. We can pass the whole thing around, print it, update it easily and cleanly

## Creating an Object

The most common way to create an object is the object literal syntax , list key-value pairs inside curly braces { }.

### Object Literal { }

```javascript
const person = {
  name:      'Alice',          // string value
  age:       25,               // number value
  city:      'Mumbai',         // string value
  isStudent: true,             // boolean value
  hobbies:   ['Reading','Coding'],  // array value
};


console.log(person);
```

Each entry is called a property. A property has a key (the label) and a value (the data), separated by a colon.

![](https://cdn.hashnode.com/uploads/covers/6783639eb96085e62fc34ca1/24e2ae4e-5ed3-4432-90b8-9daeb2a93895.png align="center")

### Empty Object - Add properties later

```javascript
onst car = {};           // start empty


car.brand = 'Toyota';    // add properties one by one
car.model = 'Camry';
car.year  = 2023;


console.log(car);
// { brand: 'Toyota', model: 'Camry', year: 2023 }
```

## Accessing Properties

Javascript gives us 2 ways to read values from an object: dot notation and bracket notation.

<table style="min-width: 337px;"><colgroup><col style="min-width: 25px;"><col style="width: 312px;"></colgroup><tbody><tr><td colspan="1" rowspan="1"><p><strong>Dot Notation&nbsp; obj.key</strong></p></td><td colspan="1" rowspan="1" colwidth="312"><p><strong>Bracket Notation&nbsp; obj['key']</strong></p></td></tr><tr><td colspan="1" rowspan="1"><p>person.name</p></td><td colspan="1" rowspan="1" colwidth="312"><p>person['name']</p></td></tr><tr><td colspan="1" rowspan="1"><p>Shorter and cleaner to write</p></td><td colspan="1" rowspan="1" colwidth="312"><p>More flexible — works with any string</p></td></tr><tr><td colspan="1" rowspan="1"><p>Key must be a valid identifier</p></td><td colspan="1" rowspan="1" colwidth="312"><p>Key can have spaces or special characters</p></td></tr><tr><td colspan="1" rowspan="1"><p>Cannot use a variable as the key</p></td><td colspan="1" rowspan="1" colwidth="312"><p>Can use a variable as the key</p></td></tr><tr><td colspan="1" rowspan="1"><p>person.first name&nbsp; -- INVALID</p></td><td colspan="1" rowspan="1" colwidth="312"><p>person['first name']&nbsp; -- VALID</p></td></tr><tr><td colspan="1" rowspan="1"><p>Use when: key is a simple known name</p></td><td colspan="1" rowspan="1" colwidth="312"><p>Use when: key is dynamic or has spaces</p></td></tr></tbody></table>

### Dot Notation - obj.key

The most common and readable approach. Use the name, a dot . , then the property name.

```javascript
const person = {
  name: 'Alice',
  age:  25,
  city: 'Mumbai',
};


console.log(person.name);   // Alice
console.log(person.age);    // 25
console.log(person.city);   // Mumbai
```

### Bracket Notation - obj\['key'\]

More flexible, essential when the key has spaces or when we need to use a variable as the key:

```javascript
const person = {
  name:       'Alice',
  'home city': 'Mumbai',   // key with a space
};


// Dot notation FAILS for keys with spaces:
// console.log(person.home city);   // SyntaxError!


// Bracket notation works:
console.log(person['name']);         // Alice
console.log(person['home city']);    // Mumbai


// Using a VARIABLE as the key:
let key = 'name';
console.log(person[key]);            // Alice
```

**Which notation should we use?**  
Use dot notation (person.name) by default. Switch to bracket notation (person\['name'\] when the key has spaces, special characters, or when the key name is stored in a variable.

## Updating Object Properties

Assign a new value to an existing key using =. Works with both notations

```javascript
const person = {
  name: 'Alice',
  age:  25,
  city: 'Mumbai',
};


// Update with dot notation
person.age  = 26;
person.city = 'Delhi';


console.log(person.age);    // 26  (updated)
console.log(person.city);   // Delhi  (updated)


// Update with bracket notation
person['name'] = 'Bob';
console.log(person.name);   // Bob  (updated)
```

**const does not freeze the object**  
We used const to declare person, yet we can still change its properties. Here is why:  
const means the VARIABLE cannot point to a different object.  
But the CONTENTS inside the object can change freely.  
We can use Object.freeze(person) if we truly want to lock everything.

```javascript
const person = { name: 'Alice' };


person.name = 'Bob';   // FINE — changing a property inside


// person = { name: 'Charlie' };  // ERROR — reassigning the variable
```

## Adding and Deleting Properties

### Adding New Properties

Add a brand new property at any time by assigning to a key that does not yet exist.

```javascript
const person = {
  name: 'Alice',
  age:  25,
};


person.email    = 'alice@example.com';   // new property
person.city     = 'Mumbai';
person.isActive = true;


console.log(person);
// {name:'Alice',age:25,email:'alice@...',city:'Mumbai',isActive:true}
```

### Deleting Properties

Use the delete operator to permanently remove a property.

```javascript
const person = {
  name: 'Alice',
  age:  25,
  city: 'Mumbai',
};


delete person.city;


console.log(person.city);   // undefined  (gone)
console.log(person);        // { name: 'Alice', age: 25 }
```

**delete removes the property permanently**  
Once deleted, the property no longer exists. If we just want to clear a value without removing the key, set it to null instead: person.city = null

## Looping through Object Properties

Objects don't have numeric indexes, so we can't use a regular for loop. Javascript provides four dedicated tools for iterating over objects properties.

**Looping Tools**

<table style="width: 680px;"><colgroup><col style="width: 90px;"><col style="width: 253px;"><col style="width: 337px;"></colgroup><tbody><tr><td colspan="1" rowspan="1" colwidth="90"><p>#</p></td><td colspan="1" rowspan="1" colwidth="253"><p><strong>Method / Tool</strong></p></td><td colspan="1" rowspan="1" colwidth="337"><p><strong>What it returns / does</strong></p></td></tr><tr><td colspan="1" rowspan="1" colwidth="90"><p><strong>1</strong></p></td><td colspan="1" rowspan="1" colwidth="253"><p><strong>Object.keys(obj)</strong></p></td><td colspan="1" rowspan="1" colwidth="337"><p><strong>Returns array of all KEYS</strong><br>e.g.&nbsp; ["name","age","city"]</p></td></tr><tr><td colspan="1" rowspan="1" colwidth="90"><p><strong>2</strong></p></td><td colspan="1" rowspan="1" colwidth="253"><p><strong>Object.values(obj)</strong></p></td><td colspan="1" rowspan="1" colwidth="337"><p><strong>Returns array of all VALUES</strong><br>e.g.&nbsp; ["Alice", 25, "Mumbai"]</p></td></tr><tr><td colspan="1" rowspan="1" colwidth="90"><p><strong>3</strong></p></td><td colspan="1" rowspan="1" colwidth="253"><p><strong>Object.entries(obj)</strong></p></td><td colspan="1" rowspan="1" colwidth="337"><p><strong>Returns array of [key,val] pairs</strong><br>e.g.&nbsp; [["name","Alice"],["age",25]]</p></td></tr><tr><td colspan="1" rowspan="1" colwidth="90"><p><strong>4</strong></p></td><td colspan="1" rowspan="1" colwidth="253"><p><strong>for...in loop</strong></p></td><td colspan="1" rowspan="1" colwidth="337"><p><strong>Iterates over each KEY</strong><br>e.g.&nbsp; name -&gt; age -&gt; city -&gt; ...</p></td></tr></tbody></table>

### for...in Loop

Iterates over each key in the object. Use the key to access the corresponding value.

```javascript
const person = {
  name: 'Alice',
  age:  25,
  city: 'Mumbai',
};


for (let key in person) {
  console.log(key + ' : ' + person[key]);
}


// Output:
// name : Alice
// age  : 25
// city : Mumbai
```

### Object.keys() - Array of all keys

```javascript
const keys = Object.keys(person);
console.log(keys);          // ['name', 'age', 'city']
console.log(keys.length);   // 3
```

### Object.values() - Array of Values

```javascript
const values = Object.values(person);
console.log(values);   // ['Alice', 25, 'Mumbai']
```

### Object.entires() - Array of \[key, value\] pairs

This gives is both key and value in every iteration.

```javascript
const entries = Object.entries(person);
console.log(entries);
// [['name','Alice'], ['age',25], ['city','Mumbai']]


for (let [key, value] of Object.entries(person)) {
  console.log(key + ' => ' + value);
}
// name => Alice
// age  => 25
// city => Mumbai
```

## Array vs Object - When to use which?

Both group multiple values together, but serve different purposes.

<table style="width: 645px;"><colgroup><col style="width: 333px;"><col style="width: 312px;"></colgroup><tbody><tr><td colspan="1" rowspan="1" colwidth="333"><p><strong>Array&nbsp; [ ]</strong></p></td><td colspan="1" rowspan="1" colwidth="312"><p><strong>Object&nbsp; { }</strong></p></td></tr><tr><td colspan="1" rowspan="1" colwidth="333"><p>Ordered list of values</p></td><td colspan="1" rowspan="1" colwidth="312"><p>Named collection of key-value pairs</p></td></tr><tr><td colspan="1" rowspan="1" colwidth="333"><p>Access by INDEX (number)</p></td><td colspan="1" rowspan="1" colwidth="312"><p>Access by KEY (string name)</p></td></tr><tr><td colspan="1" rowspan="1" colwidth="333"><p>const arr = ["Alice",25,"Mumbai"]</p></td><td colspan="1" rowspan="1" colwidth="312"><p>const obj = {name:"Alice",age:25}</p></td></tr><tr><td colspan="1" rowspan="1" colwidth="333"><p>arr[0]&nbsp; -&gt;&nbsp; Alice</p></td><td colspan="1" rowspan="1" colwidth="312"><p>obj.name&nbsp; -&gt;&nbsp; Alice</p></td></tr><tr><td colspan="1" rowspan="1" colwidth="333"><p>arr[1]&nbsp; -&gt;&nbsp; 25</p></td><td colspan="1" rowspan="1" colwidth="312"><p>obj.age&nbsp; -&gt;&nbsp; 25</p></td></tr><tr><td colspan="1" rowspan="1" colwidth="333"><p>Array.isArray(arr)&nbsp; -&gt;&nbsp; true</p></td><td colspan="1" rowspan="1" colwidth="312"><p>Array.isArray(obj)&nbsp; -&gt;&nbsp; false</p></td></tr><tr><td colspan="1" rowspan="1" colwidth="333"><p>Order matters — index is fixed</p></td><td colspan="1" rowspan="1" colwidth="312"><p>Order does not matter — keys are named</p></td></tr><tr><td colspan="1" rowspan="1" colwidth="333"><p>Use for: lists of similar items</p></td><td colspan="1" rowspan="1" colwidth="312"><p>Use for: describing one entity</p></td></tr></tbody></table>

```javascript
// Use an ARRAY for a list of similar things
const students = ['Alice', 'Bob', 'Charlie'];
const scores   = [95, 87, 72];


// Use an OBJECT to describe one entity with named properties
const student = { name:'Alice', score:95, grade:'A' };


// Combine them — array of objects (very common in real apps!)
const classroom = [
  { name:'Alice',   score:95 },
  { name:'Bob',     score:87 },
  { name:'Charlie', score:72 },
];


console.log(classroom[0].name);    // Alice
console.log(classroom[1].score);   // 87
```

## Nested Objects

Object properties can themselves be objects. This is called nesting and lets us model rich real-world data structures.

```javascript
const person = {
  name:    'Alice',
  age:     25,
  address: {
    street:  '12 MG Road',
    city:    'Mumbai',
    pincode: 400001,
  },
  hobbies: ['Reading', 'Coding', 'Hiking'],
};


// Chain dot notation to drill into nested objects
console.log(person.address.city);     // Mumbai
console.log(person.address.pincode);  // 400001


// Access array inside object
console.log(person.hobbies[0]);       // Reading
console.log(person.hobbies.length);   // 3
```

**Chain as deep as we need:**  
`person.address.city` reads from person, get address, then from that get city. We can chain many levels deep. But we should be careful that if any level is undefined or null, accessing a property on it will throw an error.

## Assignment

### Task 1 - Create a student object

```javascript
const student = {
  name:     'Rahul',
  age:      20,
  course:   'Computer Science',
  grade:    'A',
  isActive: true,
};
console.log(student);
```

### Task 2 - Access properties both ways

```javascript
console.log(student.name);        // dot notation
console.log(student['course']);    // bracket notation
```

### Task 3 - Update and add properties

```javascript
student.grade = 'A+';              // update
student.city  = 'Pune';            // add new
console.log(student.grade);        // A+
console.log(student.city);         // Pune
```

### Task 4 - Print all keys and values using a loop

```javascript
for (let key in student) {
  console.log(key + ' : ' + student[key]);
}
```

### Task 5 - Use Object.keys, .values, .entries

```javascript
console.log(Object.keys(student));
console.log(Object.values(student));


for (let [k, v] of Object.entries(student)) {
  console.log(k + ' => ' + v);
}
```

### Task 6 - Delete a property

```javascript
delete student.isActive;
console.log(student.isActive);       // undefined
console.log(Object.keys(student));   // isActive gone
```

## Summary

Here is everything we saw and learned in this article:

*   **Objects** group related data as **key-value pairs** — perfect for describing real-world entities
    
*   Create with { key: value } object literal syntax
    
*   **Dot notation** obj.key — clean and preferred for simple known keys
    
*   **Bracket notation** obj\['key'\] — use for dynamic keys, spaces, or variables
    
*   Update properties: obj.key = newValue
    
*   Add properties: obj.newKey = value (anytime, on the fly)
    
*   Delete properties: delete obj.key
    
*   for...in loops over keys; Object.keys(), .values(), .entries() return arrays
    
*   Objects stored by **reference** — copying copies the pointer, not the data
    
*   Use **arrays** for ordered lists, **objects** for named entities, and combine both for real app data
    

Objects are at the heart of JavaScript. Every API response, every user record, every component's data - it all flows through object.
