# Object Fundamentals

Course: [JavaScript](https://www.devtutorials.ai/learn/javascript) · Section: Objects
Source: https://www.devtutorials.ai/learn/javascript/objects/object-fundamentals

> What an object is, creating one with a literal or new Object(), dot and bracket access, updating, adding and deleting properties, methods and this, checking a property with in, and looping with for...in.

## What Is an Object?

**Object** = one value that keeps related information together, by **name**.

- **Property** = one `key: value` pair, like `price: 349`.
- **Key** = the name. **Value** = the data stored under it.
- **Method** = a function stored as a property.

**Simple lesson:** arrays find things by position; objects find things by name.

### A Real-World Example

Think of an *anjarai petti* (spice box): one box, many labelled sections.
A shop's product is one object: `{ name: "Lunch box", price: 349, stock: 12 }`.
The page reads `product.price` to show the price, and changes `product.stock` after a sale.

<figure className="ts-fig">
  <svg viewBox="0 0 560 170" role="img" aria-label="A box labelled product with three labelled sections: name, price and stock. A highlight moves from section to section." width="100%">
    <rect x="0" y="0" width="560" height="170" rx="12" fill="#f8fafc" stroke="#e2e8f0" />
    <text x="40" y="38" fontSize="13" fontFamily="monospace" fill="#334155">const product = &#123;</text>
    <rect x="40" y="52" width="150" height="70" rx="8" fill="#eff6ff" stroke="#2563eb" />
    <text x="115" y="80" textAnchor="middle" fontSize="12" fill="#1e40af">name</text>
    <text x="115" y="102" textAnchor="middle" fontSize="13" fontFamily="monospace" fill="#1e40af">"Lunch box"</text>
    <rect x="205" y="52" width="150" height="70" rx="8" fill="#fefce8" stroke="#ca8a04" />
    <text x="280" y="80" textAnchor="middle" fontSize="12" fill="#854d0e">price</text>
    <text x="280" y="102" textAnchor="middle" fontSize="13" fontFamily="monospace" fill="#854d0e">349</text>
    <rect x="370" y="52" width="150" height="70" rx="8" fill="#f0fdf4" stroke="#16a34a" />
    <text x="445" y="80" textAnchor="middle" fontSize="12" fill="#166534">stock</text>
    <text x="445" y="102" textAnchor="middle" fontSize="13" fontFamily="monospace" fill="#166534">12</text>
    <rect y="48" width="158" height="78" rx="10" fill="none" stroke="#dc2626" strokeWidth="3">
      <animate attributeName="x" values="36;201;366;36" keyTimes="0;0.33;0.66;1" calcMode="discrete" dur="3s" repeatCount="indefinite" />
    </rect>
    <text x="280" y="152" textAnchor="middle" fontSize="12" fill="#475569">product.name → product.price → product.stock</text>
  </svg>
  <figcaption>Each section has a label. You open it by name.</figcaption>
</figure>

The boxes print objects in JSON style, with quotes around every key. That is only the display. In your code, keys need no quotes.

## What You Will Learn

1. What an object is, and why we use one.
2. How to create objects and read properties (dot and brackets).
3. How to update, add and delete properties.
4. Methods and `this`.
5. Checking keys (`in`, `Object.hasOwn()`) and looping with `for...in`.

## Introduction to Objects

### What is an object

The variable `customer` holds one object. `name`, `city` and `orders` are its properties, inside `{ }`.

```js runnable title="One object that describes one customer"
const customer = {
  name: "Asha",
  city: "Chennai",
  orders: 3,
};

console.log(customer);
```

Expected output:

```text
{
  "name": "Asha",
  "city": "Chennai",
  "orders": 3
}
```

### Key-value pairs

Keys and values are joined by `:` and separated by commas. Values can be any type.
`Object.keys()` lists the keys; `Object.values()` lists the values.

```js runnable title="Keys are the names, values are the data"
const product = {
  title: "Desk Lamp",
  price: 1299,
  inStock: true,
};

console.log(Object.keys(product));
console.log(Object.values(product));
```

Expected output:

```text
[
  "title",
  "price",
  "inStock"
]
[
  "Desk Lamp",
  1299,
  true
]
```

### Why objects are used

Loose variables are easy to mix up. One object travels as one value: pass it to a function, put it in an array, or send it to a server.

```js runnable title="Three loose variables versus one object"
const productTitle = "Desk Lamp";
const productPrice = 1299;
const productInStock = true;
console.log(productTitle, productPrice, productInStock);

const product = { title: "Desk Lamp", price: 1299, inStock: true };
console.log(product.title, product.price, product.inStock);
```

Expected output:

```text
Desk Lamp 1299 true
Desk Lamp 1299 true
```

## Creating Objects

### Object literal, new Object()

- **Object literal** = written directly with `{ }`. Use this.
- `new Object()` makes an empty object, then you add properties one by one. You see it in older code.

```js runnable title="The same object, built two ways"
const literalOrder = { id: 101, status: "shipped" };

const builtOrder = new Object();
builtOrder.id = 101;
builtOrder.status = "shipped";

console.log(literalOrder);
console.log(builtOrder);
```

Expected output:

```text
{
  "id": 101,
  "status": "shipped"
}
{
  "id": 101,
  "status": "shipped"
}
```

**Why "literal"?** You write the values literally, right there in the code.

## Accessing Properties

### Dot notation

`customer.city` reads the `city` property. A missing key gives `undefined`, not an error.

```js runnable title="Reading properties with a dot"
const customer = { name: "Ravi", city: "Pune", orders: 5 };

console.log(customer.name);
console.log(customer.city);
console.log(customer.email);
```

Expected output:

```text
Ravi
Pune
undefined
```

### Bracket notation

`customer["city"]` does the same, but brackets also work with:

- names with spaces: `customer["home phone"]`
- a key stored in a variable: `customer[field]`

```js runnable title="Brackets take a string, or a variable that holds one"
const customer = { name: "Ravi", city: "Pune", "home phone": "020-5550-1234" };

console.log(customer["city"]);
console.log(customer["home phone"]);

const field = "name";
console.log(customer[field]);
console.log(customer.field);
```

Expected output:

```text
Pune
020-5550-1234
Ravi
undefined
```

`customer.field` looks for a key literally called `field`, so it gives `undefined`.

## Modifying Objects

You can change an object even in a `const`. `const` only stops you from replacing the **whole** object.

### Updating values

Assign to an existing key, and the old value is replaced.

```js runnable title="Assigning to an existing key replaces its value"
const order = { id: 101, status: "pending", total: 450 };

order.status = "shipped";
order["total"] = 520;

console.log(order);
```

Expected output:

```text
{
  "id": 101,
  "status": "shipped",
  "total": 520
}
```

### Adding new properties

Assign to a key that does not exist yet, and JavaScript creates it.

```js runnable title="Assigning to a new key adds it"
const order = { id: 101, status: "shipped" };

order.courier = "BlueDart";
order["tracking code"] = "BD-88213";

console.log(order);
console.log(Object.keys(order).length);
```

Expected output:

```text
{
  "id": 101,
  "status": "shipped",
  "courier": "BlueDart",
  "tracking code": "BD-88213"
}
4
```

### Deleting properties

`delete obj.key` removes the key. Setting it to `undefined` keeps the key, just empty.

```js runnable title="delete removes the key, undefined only empties it"
const withDelete = { id: 101, coupon: "SAVE10" };
const withUndefined = { id: 101, coupon: "SAVE10" };

delete withDelete.coupon;
withUndefined.coupon = undefined;

console.log(withDelete.coupon, withUndefined.coupon);
console.log(Object.keys(withDelete));
console.log(Object.keys(withUndefined));
```

Expected output:

```text
undefined undefined
[
  "id"
]
[
  "id",
  "coupon"
]
```

`const b = a` does not copy an object. Both names share one object, so a change through one shows through the other. **Object Operations** shows how to copy.

## Object Methods

### Functions inside objects

Write `describe() { ... }` inside the object. Call it with `cart.describe()`. Without `()`, nothing runs.

```js runnable title="A method is a function stored as a property"
const cart = {
  owner: "Meera",
  describe() {
    return "This cart belongs to a customer.";
  },
};

console.log(typeof cart.describe);
console.log(cart.describe());
```

Expected output:

```text
function
This cart belongs to a customer.
```

### Calling methods with this

Inside a method, `this` = the object before the dot. So `this.total` means `cart.total`.

```js runnable title="this points at the object before the dot"
const cart = {
  owner: "Meera",
  items: 3,
  total: 2450,
  summary() {
    return this.owner + " has " + this.items + " items worth " + this.total + " rupees.";
  },
  addItem(price) {
    this.items = this.items + 1;
    this.total = this.total + price;
  },
};

console.log(cart.summary());
cart.addItem(300);
console.log(cart.summary());
```

Expected output:

```text
Meera has 3 items worth 2450 rupees.
Meera has 4 items worth 2750 rupees.
```

Write methods as `summary() { ... }` or with `function`. An arrow function has no `this` of its own, so `this.owner` is `undefined`.

## Property Validation

### Checking if a property exists

A key can exist and still hold `undefined`, so `!== undefined` is not enough.
`Object.hasOwn(obj, "key")` asks "is this key really here?"

```js runnable title="Comparing with undefined cannot see every case"
const profile = { name: "Kiran", discount: 0, nickname: undefined };

console.log(profile.discount !== undefined);
console.log(profile.nickname !== undefined);
console.log(profile.phone !== undefined);
console.log(Object.hasOwn(profile, "nickname"));
console.log(Object.hasOwn(profile, "phone"));
```

Expected output:

```text
true
false
false
true
false
```

### in operator

`"phone" in profile` gives `true` or `false`. It is true even when the value is `0` or `undefined`.

```js runnable title="in answers whether the key is there at all"
const profile = { name: "Kiran", discount: 0, nickname: undefined };

console.log("name" in profile);
console.log("nickname" in profile);
console.log("phone" in profile);

if ("discount" in profile) {
  console.log("Discount on record:", profile.discount);
}
```

Expected output:

```text
true
true
false
Discount on record: 0
```

`in` also finds inherited keys. `Object.hasOwn()` checks only the object's own keys. For plain data objects, both give the same answer.

## Object Iteration

### for...in loop

`for (const key in obj)` runs once per key. The key is in a variable, so read the value with `obj[key]`.

```js runnable title="for...in hands you each key, one at a time"
const stock = { pens: 120, notebooks: 45, markers: 30 };

for (const item in stock) {
  console.log(item + ": " + stock[item]);
}

let totalUnits = 0;
for (const item in stock) {
  totalUnits = totalUnits + stock[item];
}
console.log("Total units:", totalUnits);
```

Expected output:

```text
pens: 120
notebooks: 45
markers: 30
Total units: 195
```

Inside `for...in`, always use `obj[key]`. `obj.key` looks for a key named "key".

## Objects on a Web Page

One product object fills the card. A button calls a method that uses `this` to change the stock.

```js runnable preview="price-card" title="A product card driven by one object"
const product = {
  name: "Lunch box",
  price: 349,
  stock: 3,
  sell() {
    if (this.stock > 0) this.stock -= 1;
  },
};

function draw() {
  document.querySelector("#name").textContent = product.name;
  document.querySelector("#price").textContent = "₹" + product.price;
  document.querySelector("#stock").textContent = product.stock > 0 ? `Stock: ${product.stock}` : "Sold out";
}

const buy = document.createElement("button");
buy.textContent = "Buy one";
buy.addEventListener("click", () => {
  product.sell();
  draw();
  console.log("stock is now", product["stock"]);
});
document.querySelector("#card").append(buy);
draw();
```

Press **Buy one** three times. On the third press the card says **Sold out**.

**Easy way to remember:** dot when you **know** the name; brackets when the name is in a **variable** or has a space.

## TL;DR

- An object stores `key: value` pairs; read with `obj.key` or `obj["key"]`.
- Missing keys give `undefined`, not an error.
- Assign to update or add; `delete` removes a key.
- A method is a function property; `this` is the object before the dot.
- Check keys with `in` or `Object.hasOwn()`; loop with `for...in` and `obj[key]`.

## Try this

In the `for...in` example, add `erasers: 60` to `stock`. The loop now runs four times and the total grows from 195 to 255, with no change to the loop.

## Check Yourself

## Common mistakes

| Mistake | Wrong idea | Correct idea | What goes wrong |
|---|---|---|---|
| `customer.field` for a key in a variable | The dot reads the variable | Use `customer[field]` | `undefined` |
| `customer.home phone` | Dots allow spaces | Use `customer["home phone"]` | A syntax error |
| `order.stauts` (typo) | A wrong key throws | It gives `undefined` silently | The bug hides |
| `order.key = undefined` to remove | That deletes the key | Use `delete order.key` | The key still shows in `Object.keys()` |
| An arrow function as a method | Arrows get `this` | Use `name() { ... }` | `this.owner` is `undefined` |
| `obj.key` inside `for...in` | It reads the current key | Use `obj[key]` | Every value is `undefined` |

## Quick reference

<div className="tscroll">

| Syntax | Meaning |
|---|---|
| `{ name: "Asha", orders: 3 }` | create an object with an object literal |
| `new Object()` | create an empty object, the older way |
| `object.key` | read a property by its exact name |
| `object["key"]` or `object[variable]` | read a property by a string or by a variable that holds one |
| `object.key = value` | update the key, or add it if it does not exist |
| `delete object.key` | remove the key and its value completely |
| `method() { … }` | a function stored inside an object |
| `this.key` | inside a method, a property of the object the method was called on |
| `"key" in object` | `true` when the key exists, even if its value is `undefined` |
| `Object.hasOwn(object, "key")` | `true` when the object itself has the key |
| `for (const key in object) { … }` | run a block once for each key |

</div>

## Exercises

## What to Remember

- Objects group related data by name.
- Brackets for variable keys; dots for known keys.
- `this` lets a method use its own object.

Next: **Object Operations**. Nested objects, destructuring, spread and rest, copying, and keys from variables.
