Object Fundamentals

By Syncfusion®, Inc. · Last updated

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.

const product = {

name "Lunch box"

price 349

stock 12

product.name → product.price → product.stock

Each section has a label. You open it by name.

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 { }.

One object that describes one customer

const customer = {
  name: "Asha",
  city: "Chennai",
  orders: 3,
};

console.log(customer);

Expected output:

{
  "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.

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:

[
  "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.

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:

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.

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:

{
  "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.

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:

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]

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:

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.

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:

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

Adding new properties

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

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:

{
  "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.

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:

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.

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:

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.

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:

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?"

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:

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.

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:

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].

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:

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.

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

MistakeWrong ideaCorrect ideaWhat goes wrong
customer.field for a key in a variableThe dot reads the variableUse customer[field]undefined
customer.home phoneDots allow spacesUse customer["home phone"]A syntax error
order.stauts (typo)A wrong key throwsIt gives undefined silentlyThe bug hides
order.key = undefined to removeThat deletes the keyUse delete order.keyThe key still shows in Object.keys()
An arrow function as a methodArrows get thisUse name() { ... }this.owner is undefined
obj.key inside for...inIt reads the current keyUse obj[key]Every value is undefined

Quick reference

SyntaxMeaning
{ name: "Asha", orders: 3 }create an object with an object literal
new Object()create an empty object, the older way
object.keyread 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 = valueupdate the key, or add it if it does not exist
delete object.keyremove the key and its value completely
method() { … }a function stored inside an object
this.keyinside a method, a property of the object the method was called on
"key" in objecttrue 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

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.