Topic 48 of 59 JavaScript Objects, Arrays & Advanced Data Structures Interactive Tutorial

JavaScript Objects: Creating, Reading, Updating, and Managing Properties

23 mins read Last updated: 22 Aug 2026 14453 views
Quick Summary & Key Takeaway Target Skill Level: Beginner to Advanced ES6+

Bottom-Line Answer: JavaScript (JS) is a high-level, single-threaded, just-in-time (JIT) compiled programming language with first-class functions that conforms to the ECMAScript specification. It powers dynamic client-side web interactivity alongside HTML and CSS, and executes backend server runtimes via Node.js, Deno, and Bun.

Target Audience: Frontend developers, full-stack engineers, students & QA testers.
Prerequisites: Basic HTML semantics & fundamental CSS styling rules.
Primary Use Cases: Dynamic web UI, DOM manipulation, asynchronous REST APIs, Node.js backend services.

What is JavaScript Objects? Core Concept & Direct Summary

Core Objective & Problem Statement

How do you manipulate object properties in JavaScript?

Direct Answer Summary
Read/write properties via dot notation (obj.key) or bracket notation (obj['key']); delete properties using delete obj.key.

Think about the data in any real app:

  • Auser: name, email, age, avatar 🧑
  • Aproduct: title, price, stock, rating 📦
  • Ablog post: heading, author, date, content 📝

None of these fit in a single variable — they'rebundlesof related information. That's exactly whatobjectsare for: labeled containers that group related data (and behavior) into one package.

You first met objects as a data type, built them from blueprints, and added guards with getters/setters This lesson is the complete hands-on toolkit: every way tocreate, read, update, delete, and manageobject properties — the CRUD operations you'll perform daily as a developer. Let's unpack the box. 📦

How Does JavaScript Objects Work? In-Depth Mechanics & Architecture

Bracket notation enables dynamic property access using variable keys or keys containing spaces.

Creating Objects: The Four Ways 🏗️

① Object Literal — The Everyday Way ⭐

Curly braces withkey: valuepairs — this is how 95% of objects are born:

script.js
Run Online
const user = {
  name: "Priya", // string  age: 22,                   // number  isMember: true,            // boolean  skills: ["HTML", "CSS"],   // array — objects hold anything!  address: {
  // nested object ✅    city: "Mumbai",    pin: 400001
}
};

② Empty Object + Add Properties Later

script.js
Run Online
const cart = {
};
// start emptycart.item = "Keyboard";          // fill it up as you gocart.price = 1299;

③ From a Class — The Factory (Lesson 23)

script.js
Run Online
class User {
  constructor(name) {
    this.name = name;
  }
}const user1 = new User("Amit");
// one blueprint, many objects

④ Object.create() — The Rare One

script.js
Run Online
const proto = {
  greet() {
    return "Hi!";
  }
};
const obj = Object.create(proto);
// creates with a custom prototype

You'll meet this in advanced prototype work — for now, know it exists and stick with literals.


Reading Properties: Dot vs Bracket 🔑

Two ways to read — and knowingwheneach works is a classic interview question:

Dot Notation — The Default ✅

script.js
Run Online
console.log(user.name);
// "Priya"console.log(user.address.city);   // "Mumbai" — chain through nesting

Bracket Notation — The Flexible One 🎯

script.js
Run Online
console.log(user["name"]);
// "Priya" — same result

Brackets shine in three situations dots can't handle:

script.js
Run Online
// ① Dynamic keys — the property name lives in a variable:
const key = "age";
console.log(user[key]);
// 22 ✅ — dots can't do this!
// ② Keys with spaces or special characters:
const prefs = {
  "theme color": "dark"
};
console.log(prefs["theme color"]);
// ✅ brackets required
// prefs.theme color               // ❌ syntax error!
// ③ Keys built on the fly:
const id = 42;
const responses = {
  "user-42": "ok"
};
console.log(responses["user-" + id]);
// "ok" ✅

The Comparison Card 🃏

SituationDot.Bracket[ ]
Fixed, known property✅user.name✅user["name"]
Property name in a variable❌✅user[key]
Keys with spaces/dashes❌✅
Looping through keys❌✅ (Lesson 17's for…in!)
Readability✅ cleanerslightly noisier

Rule:use dots by default; switch to brackets when the key is dynamic.

⚠️ Accessing What Doesn't Exist

script.js
Run Online
console.log(user.phone);
// undefined — no error, just undefined 🤫
console.log(user.phone.number);
// ❌ TypeError! — reading OF undefined
// ✅ Safe version (optional chaining — Lesson 6):
console.log(user?.phone?.number);
// undefined — no crash ✅

Updating & Adding Properties ✏️

Same syntax for both — if the key exists, it'supdated; if not, it'screated:

script.js
Run Online
const product = {
  title: "Mouse", price: 599
};
// Update existing:
product.price = 499;
// ✏️ updated
// Add brand new:
product.stock = 25;
// ➕ created on the spot!
product["in stock"] = true;
// brackets work too
console.log(product);
// { title: "Mouse", price: 499, stock: 25, "in stock": true }

⚠️ The const confusion — settled forever:constpreventsre-assigning the variable, not changing its contents (Lessons 4/14!):

script.js
Run Online
const user = {
  name: "Priya"
};
user.name = "Amit";
// ✅ fine — contents can change
user.age = 22;
// ✅ fine
user = {
};
// ❌ TypeError — can't re-point the variable

(Need true immutability?Object.freeze(user)locks contents too — coming below!)


Deleting Properties 🗑️

Thedeleteoperator removes a key entirely:

script.js
Run Online
const user = {
  name: "Priya", tempToken: "abc123", age: 22
};
delete user.tempToken;
// 🗑️ gone
console.log(user.tempToken);
// undefined
console.log(user);
// { name: "Priya", age: 22 }

The modern non-destructive alternative— create a copywithoutthe key using rest (Lesson 14's spread family!):

script.js
Run Online
const {
  tempToken, ...cleanUser
} = user;
// pull out tempToken, keep the rest
console.log(cleanUser);
// { name: "Priya", age: 22 } ✅
// original untouched — the React/Redux way!

Checking & Listing Properties 🔍

Does a Property Exist? —inand friends

script.js
Run Online
const user = {
  name: "Priya", age: 22
};
console.log("name" in user);
// true ✅
console.log("phone" in user);
// false
// The gotcha: a key can exist with an undefined value!
const data = {
  result: undefined
};
console.log("result" in data);
// true — key EXISTS
console.log(data.result);
// undefined — value is empty
console.log(data.hasOwnProperty("result"));
// true — the classic checker ✅

Rule:"key" in objchecksexistence;obj.key === undefinedonly checks thevalue. For validation, existence is usually what you mean.

Listing Everything: The Object Trio 🎻

The three methods you'll use constantly:

script.js
Run Online
const product = {
  title: "Keyboard", price: 1299, stock: 15
};
Object.keys(product);
// ["title", "price", "stock"] — the keys
Object.values(product);
// ["Keyboard", 1299, 15] — the values
Object.entries(product);
// [["title","Keyboard"], ["price",1299], …] — pairs

All three returnarrays— which means every array skill you have (Lesson 17's loops, Lesson 41's methods) now works on objects:

script.js
Run Online
// Loop the keys:
Object.keys(product).forEach(key => {
  console.log(`${key}: ${product[key]}`);
  // brackets — dynamic keys! 🎯
});
// Loop the pairs directly (the cleanest way):
Object.entries(product).forEach(([key, value]) => {
  console.log(`${key} → ${value}`);
});
// Real-world: find expensive items in a price list:
const prices = {
  keyboard: 1299, mouse: 599, cable: 199
};
Object.entries(prices) .filter(([item, price]) => price > 500) // filter pairs!
.forEach(([item, price]) => console.log(`💰 ${item}: ₹${price}`));
// 💰 keyboard: ₹1299
// 💰 mouse: ₹599

Memory hook:keys= labels 🏷️ ·values= contents 🎁 ·entries= both, as pairs 👫


Merging & Copying Objects 🧬


Quick refresh fromLesson 14— spread is the modern way:

script.js
Run Online
const defaults = {
  theme: "light", fontSize: 14
};
const userPrefs = {
  fontSize: 18
};
const settings = {
  ...defaults, ...userPrefs
};
console.log(settings);
// { theme: "light", fontSize: 18 } — last wins! ✅
// True copy:
const copy = {
  ...defaults
};
// The older way you'll see in legacy code:
const merged = Object.assign( {
}, defaults, userPrefs);
// same result

Freezing Objects ❄️

script.js
Run Online
const config = Object.freeze( {
  appName: "MyShop", version: "2.0"
});
config.version = "3.0";
// silently ignored (TypeError in strict mode!)
delete config.appName;
// also blocked
console.log(config.version);
// "2.0" — frozen solid ❄️

Object.freeze= read-only object. (Note: it'sshallow— nested objects inside stay editable, just like spread's shallow-copy trap from Lesson 14!)


🛠️ Mini Project: Inventory Manager 📦

Every skill from this lesson in one tiny system:

script.js
Run Online
// 📦 Inventory Manager — full object CRUD
const inventory = {
  keyboard: {
    price: 1299, stock: 15
  }, mouse: {
    price: 599, stock: 0
  }
};
// ① CREATE/UPDATE — add or restock a product:
function addProduct(name, price, stock) {
  if (name in inventory) {
    // existence check!
    inventory[name].stock += stock;
    // update existing
    console.log(`📦 Restocked ${name}: +${stock}`);
  } else {
    inventory[name] = {
      price, stock
    };
    // add new
    console.log(`✨ New product: ${name}`);
  }
}// ② READ — price lookup with safety:
function getPrice(name) {
  return inventory[name]?.price ?? "not found 🔍";
  // ?. + ?? — Lesson 6!
}// ③ DELETE — discontinue a product:
function discontinue(name) {
  if (delete inventory[name]) {
    console.log(`🗑️ ${name} discontinued`);
  }
}// ④ REPORT — the trio in action:
function printReport() {
  console.log("\n📊 INVENTORY REPORT");
  Object.entries(inventory).forEach(([name, info]) => {
    const status = info.stock > 0 ? `${info.stock} in stock ✅` : "OUT OF STOCK ⚠️";
    console.log(`${name}: ₹${info.price} — ${status}`);
  });
  console.log(`Total products: ${Object.keys(inventory).length}`);
}addProduct("monitor", 8999, 5);
// ✨ New product
addProduct("mouse", 599, 10);
// 📦 Restocked
console.log(`Mouse price: ${getPrice("mouse")}`);
// 599
console.log(`Cable price: ${getPrice("cable")}`);
// not found 🔍
discontinue("keyboard");
// 🗑️ gone
printReport();

Output:

script.js
Run Online
✨ New product: monitor📦 Restocked mouse: +10Mouse price: 599Cable price: not found 🔍🗑️ keyboard discontinued📊 INVENTORY REPORTmouse: ₹599 — 10 in stock ✅monitor: ₹8999 — 5 in stock ✅Total products: 2

Existence checks, optional chaining, dynamic keys, the Object trio — this is exactly how real inventory/admin dashboards manage data. 🏆

Common Beginner Mistakes (And Fixes)

❌ Mistake🔍 What Happens✅ Fix
user.keywhen key is a variableReads a literal property named "key" 😱user[key]— brackets for variables
obj.a.bwhenamight not existTypeError crashobj?.a?.boptional chaining
Assumingconstobjects can't changeConfusion whenobj.x = 1worksconst locks the variable, not contents
key in objvsobj.key !== undefinedmixupsWrong validation logicin= exists; value check = has content
Forgetting Object.keys returns an ARRAYTrying object methods on itIt's an array — use forEach/map/for…of
delete obj(the whole object)false — variables can't be deleteddelete obj.property— properties only
Expecting spread to deep-copyNested edits leak both ways (Lesson 14!)structuredClone()for nesting

Quick Self-Check: Lesson 47 Quiz 🧠

  1. What's the output?
    script.js
    Run Online
    const key = "score";
    const game = {
      score: 100
    };
    console.log(game.key, game[key]);
  2. How do you check whether a propertyexists(even if its value is undefined)?
  3. What doObject.keys(),Object.values(), andObject.entries()each return?
  4. Why doesconst user = {}; user.name = "Sam";work — isn't const immutable?
  5. What's the output?
    script.js
    Run Online
    const a = {
      x: 1
    };
    const b = {
      ...a, x: 2, y: 3
    };
    console.log(b);

(Answers: 1. undefined 100 — dot reads a literal "key" property; brackets evaluate the variable · 2."prop" in obj(or hasOwnProperty) — it checks existence, not the value · 3. keys → array of property names; values → array of values; entries → array of [key, value] pairs · 4. const prevents reassigning the variable to a new object; changing properties inside is always allowed · 5.{ x: 2, y: 3 }— later properties override spread ones)

JavaScript Decision Matrix & Syntax Comparison

Understanding the mechanical differences between variable declarations and execution environments is critical for writing performant, bug-free modern JavaScript.

Variable Declarations: var vs let vs const
Feature / Propertyvar (Legacy ES5)let (Modern ES6+)const (Modern ES6+)
ScopeFunction ScopeBlock Scope ({})Block Scope ({})
Hoisting BehaviorHoisted (initialized as undefined)Hoisted (Temporal Dead Zone - ReferenceError)Hoisted (Temporal Dead Zone - ReferenceError)
Reassignable✓ Yes✓ Yes✗ No (Immutable binding)
Redeclarable in Same Scope✓ Yes (Error-prone)✗ No (SyntaxError)✗ No (SyntaxError)
Window Object BindingCreates property on windowDoes not attach to windowDoes not attach to window
Environment Decision Matrix: Browser Client-Side vs Node.js Server-Side
DimensionClient-Side (Web Browser)Server-Side (Node.js / Deno)
Global Objectwindow, document, navigatorglobal, process, globalThis
DOM & UI Manipulation✓ Full access (document.querySelector)✗ No DOM (Headless / Non-UI)
File System & OS Access✗ Blocked (Sandboxed security)✓ Full access (fs, os, child_process)
Primary FocusInteractive UI, animations, client stateREST APIs, microservices, databases, I/O streaming

Runnable JavaScript Code Example & Practical Implementation

script.js
Run Online
const book = {
  title: 'JS Guide', author: 'Dan'
};
book.year = 2024;
// Add property
book['title'] = 'Mastering JS';
// Update property
delete book.author;
// Delete property
console.log(book);

Frequently Asked Questions & Technical Interview Insights

Technical Interview & Viva Questions

Frequently asked questions for frontend & full-stack roles
Q

Q: How do Object.freeze() and Object.seal() differ?

A: Object.freeze() prevents adding, deleting, or modifying existing properties; Object.seal() prevents adding or deleting properties but allows modifying existing ones.

Related Tools, Tutorials & Authoritative References

Recommended Interactive Tools

Authoritative Standards & Citations