Tutorials JavaScript Objects Basics
Ch 35 / 78
Chapter 35 Beginner 9 min read JavaScript

Objects Basics

An object is JavaScript's most fundamental data structure — a collection of key: value pairs that can hold any type of data, including functions and other objects. Almost everything in JavaScript is an object or behaves like one. Mastering object creation, property access, mutation, and iteration is essential for writing any real-world JavaScript application.

What you'll learn
Three ways to create objects — literal, constructor, Object.create()
Dot notation vs bracket notation — when to use which
Add, update, and delete properties at runtime
Methods inside objects — functions as property values
Iterate object keys, values, and entries
Reference vs value — why objects behave differently from primitives

What is an Object?

An object is a collection of named values. Each entry is called a property and consists of a key (always a string or Symbol) and a value (any data type — number, string, boolean, array, function, or another object). There are three main ways to create one:

{ }
Object Literal
The most common way. Write key-value pairs directly inside curly braces. Clean, readable, and used in 95% of real code.
Best for: creating a single, well-known object with a fixed shape.
new Object()
Object Constructor
Uses the built-in Object constructor. Produces the same result as a literal but is more verbose — rarely used today.
Best for: legacy codebases or when the creation needs to be explicit.
Object.create()
Object.create()
Creates a new object with a specified prototype object. Useful for prototype-based inheritance without using classes.
Best for: setting up prototype chains manually or creating null-prototype objects.

Object Anatomy & Syntax

Every key-value pair is separated by a colon : and properties are separated by commas. Values can be any JavaScript type including functions, arrays, and nested objects:

const user = {
  name: "Alice", // string value
  age: 28, // number value
  isAdmin: true, // boolean value
  scores: [92, 88, 95], // array value
  address: { city: "Surat" }, // nested object
  greet: function() { /* method */ },
};
Key — always a string (quotes are optional for valid identifiers) Value — any JS type: string, number, boolean, array, object, function Method — a function stored as a property value Trailing comma after last property is valid and recommended
JavaScript — Creating Objects
// ── Object Literal (most common) ────────────────────────────
const product = {
name: "Laptop",
price: 800,
inStock: true,
tags: ["electronics", "computers"],
specs: { ram: "16GB", storage: "512GB" },
};

// ── Empty object — add properties later ─────────────────────
const config = {};

// ── new Object() — produces identical result ─────────────────
const car = new Object();
car.make = "Toyota";
car.model = "Camry";
car.year = 2024;

// ── Object.create() — set explicit prototype ─────────────────
const animal = { breathes: true };
const dog = Object.create(animal);
dog.name = "Rex";
console.log(dog.breathes); // true ← inherited from animal prototype

// ── Keys with spaces or special chars — use quotes ───────────
const data = {
"first-name": "Alice", // hyphen in key needs quotes
"2024-revenue": 45000, // starts with digit — needs quotes
normalKey: "no quotes needed",
};

Accessing Properties

JavaScript provides two ways to read a property's value — dot notation for clean, predictable keys and bracket notation for dynamic or special-character keys. Both work identically under the hood:

Dot Notation — obj.key
✓ Cleaner and preferred for known, valid identifier keys
✓ Key must be a valid JS identifier — no spaces or hyphens
✗ Cannot use a variable as the key — it's literal
✗ Cannot access keys that start with numbers or contain symbols
Bracket Notation — obj["key"]
✓ Dynamic keys — use a variable: obj[varName]
✓ Works with any string — spaces, hyphens, symbols
✓ Essential for computed property names at runtime
! Slightly more verbose — use only when dot notation doesn't work
JavaScript — Property Access
const user = { name: "Alice", age: 28, "home-city": "Surat" };

// ── Dot notation ─────────────────────────────────────────────
console.log(user.name); // "Alice"
console.log(user.age); // 28

// ── Bracket notation ─────────────────────────────────────────
console.log(user["name"]); // "Alice"
console.log(user["home-city"]); // "Surat" ← hyphen key — must use brackets

// ── Dynamic key via variable ─────────────────────────────────
const field = "age";
console.log(user[field]); // 28 ← bracket resolves the variable
// user.field would give undefined (looks for property named "field")

// ── Accessing nested properties ──────────────────────────────
const company = { address: { city: "Surat", pin: "395001" } };
console.log(company.address.city); // "Surat"
console.log(company["address"]["pin"]); // "395001"

// ── Non-existent property returns undefined (no error) ───────
console.log(user.phone); // undefined

// ── Optional chaining — safe deep access ─────────────────────
console.log(user.address?.city); // undefined (no error if address is missing)
Rule of Thumb
Use dot notation whenever the key is a known, valid identifier. Switch to bracket notation when the key contains special characters, starts with a digit, or when the key is stored in a variable and computed at runtime.

Add, Update & Delete Properties

Objects in JavaScript are mutable by default — you can add new properties, change existing values, and remove properties at any time after creation, even on const objects (the binding is constant, not the contents):

Create
Add a new property
obj.newKey = value;
obj["newKey"] = value;
Assign to a key that doesn't exist yet — JavaScript creates it automatically.
Read
Read a property value
obj.key
obj["key"]
Returns the value or undefined if the key doesn't exist. Never throws.
Update
Update an existing property
obj.key = newValue;
obj["key"] = newValue;
Same syntax as create — overwrites the value if the key already exists.
Delete
Remove a property
delete obj.key;
delete obj["key"];
Removes the property entirely. After deletion, accessing it returns undefined.
JavaScript — Add, Update & Delete
const user = { name: "Alice", age: 28 };

// ── ADD — new properties ─────────────────────────────────────
user.email = "alice@example.com";
user["phone"] = "9876543210";
console.log(user);
// { name: "Alice", age: 28, email: "...", phone: "..." }

// ── UPDATE — existing properties ─────────────────────────────
user.age = 29; // overwrite
user.name = user.name.toUpperCase(); // "ALICE"

// ── DELETE — remove properties ───────────────────────────────
delete user.phone;
console.log(user.phone); // undefined

// ── const doesn't prevent property mutation! ─────────────────
const config = { debug: true };
config.debug = false; // ✅ OK — mutating the object, not re-assigning config
// config = {}; // ❌ Error — cannot re-assign a const binding

// ── Check if a property exists ───────────────────────────────
console.log("name" in user); // true
console.log("salary" in user); // false
console.log(user.hasOwnProperty("age")); // true
const ≠ Immutable
Declaring an object with const means the variable binding is constant — you cannot reassign the variable to a different object. But the object's contents are still fully mutable — you can freely add, change, and delete its properties. To truly freeze an object, use Object.freeze(obj).

Object Methods

When a function is stored as an object property, it is called a method. ES6 introduced a cleaner shorthand for defining methods. Inside a method, this refers to the object the method belongs to:

JavaScript — Object Methods
// ── Traditional method syntax ────────────────────────────────
const user = {
name: "Alice",
age: 28,

greet: function() {
console.log(`Hello, I'm ${this.name}`);
},
};

// ── ES6 shorthand method syntax (preferred) ──────────────────
const product = {
name: "Laptop",
price: 800,
tax: 0.18,

totalPrice() {
return this.price * (1 + this.tax);
},

describe() {
return `${this.name} — $${this.totalPrice().toFixed(2)}`;
},
};

console.log(product.totalPrice()); // 944
console.log(product.describe()); // "Laptop — $944.00"

// ── Add a method after creation ──────────────────────────────
user.birthday = function() {
this.age++;
console.log(`Happy birthday! Now ${this.age}`);
};
user.birthday(); // Happy birthday! Now 29

// ── Arrow functions as methods — avoid! ─────────────────────
const bad = {
name: "Bob",
greet: () => console.log(this.name), // ❌ this is undefined/window
}; // Arrow functions don't have their own 'this'

Iterating Over Objects

Unlike arrays, plain objects are not directly iterable with for...of. But JavaScript provides several ways to loop through an object's keys, values, or both. The modern Object static methods are the cleanest approach:

JavaScript — Iterating Objects
const scores = { Alice: 92, Bob: 87, Carol: 95 };

// ── for...in — iterates own + inherited enumerable keys ───────
for (const key in scores) {
if (scores.hasOwnProperty(key)) { // guard against inherited props
console.log(`${key}: ${scores[key]}`);
}
} // Alice: 92 Bob: 87 Carol: 95

// ── Object.keys() — array of own property keys ───────────────
const keys = Object.keys(scores);
console.log(keys); // ["Alice", "Bob", "Carol"]

// ── Object.values() — array of values ────────────────────────
const vals = Object.values(scores);
console.log(vals); // [92, 87, 95]

// ── Object.entries() — array of [key, value] pairs ───────────
const entries = Object.entries(scores);
console.log(entries);
// [["Alice", 92], ["Bob", 87], ["Carol", 95]]

// ── Loop with entries + destructuring ────────────────────────
for (const [name, score] of Object.entries(scores)) {
console.log(`${name} scored ${score}`);
}

// ── Sum all values using reduce on entries ───────────────────
const total = Object.values(scores).reduce((sum, s) => sum + s, 0);
console.log(total); // 274

// ── Object.fromEntries() — array of pairs → object ───────────
const doubled = Object.fromEntries(
Object.entries(scores).map(([k, v]) => [k, v * 2])
);
console.log(doubled); // { Alice: 184, Bob: 174, Carol: 190 }

Objects Are Reference Types

This is one of the most important — and most misunderstood — aspects of objects. Unlike primitives (numbers, strings, booleans) which are copied by value, objects are stored and copied by reference. Multiple variables can point to the same object in memory:

JavaScript — Reference vs Value
// ── Primitives — copied by VALUE ─────────────────────────────
let a = 10;
let b = a; // b gets a copy of the value
b = 99;
console.log(a); // 10 ← unchanged

// ── Objects — copied by REFERENCE ────────────────────────────
const user1 = { name: "Alice", age: 28 };
const user2 = user1; // user2 points to the SAME object in memory
user2.name = "Bob";
console.log(user1.name); // "Bob" ← user1 was also changed!

// ── Equality compares references, not content ─────────────────
const x = { val: 1 };
const y = { val: 1 };
console.log(x === y); // false ← different objects in memory
console.log(x === x); // true ← same reference

// ── Shallow clone — break the reference ──────────────────────
const original = { name: "Alice", age: 28 };
const spread = { ...original }; // spread (shallow)
const assign = Object.assign({}, original); // Object.assign (shallow)
const deep = structuredClone(original); // deep clone (ES2022)

spread.name = "Bob";
console.log(original.name); // "Alice" ← original is safe

// ── Shallow vs Deep — nested object still shared ─────────────
const obj = { name: "Alice", scores: [90, 80] };
const shallowCopy = { ...obj };
shallowCopy.scores.push(70); // mutates nested array!
console.log(obj.scores); // [90, 80, 70] ← both share it
Deep Clone in 2025
Use structuredClone(obj) for a full deep copy — available in all modern browsers and Node.js 17+. It handles nested objects, arrays, dates, and more. The old JSON.parse(JSON.stringify(obj)) trick breaks for dates, functions, undefined, and circular references.

Useful Object Static Methods

The Object class provides a rich set of static utility methods for working with objects — from copying properties to freezing, checking keys, and converting between objects and arrays:

Method What it does Returns
Object.keys(obj) Returns all own enumerable property keys Array<string>
Object.values(obj) Returns all own enumerable property values Array<any>
Object.entries(obj) Returns [key, value] pairs for all own enumerable props Array<[k,v]>
Object.fromEntries(iter) Converts an iterable of [key, value] pairs into an object Object
Object.assign(target, src) Copies own enumerable props from source(s) to target — shallow merge target Object
Object.freeze(obj) Makes object immutable — no add, update, or delete allowed frozen Object
Object.isFrozen(obj) Checks if the object has been frozen boolean
Object.create(proto) Creates a new object with the specified prototype new Object
Object.hasOwn(obj, key) Returns true if object has the key as own property (ES2022) boolean
JavaScript — Object Utility Methods
const user = { name: "Alice", age: 28, role: "admin" };

// ── Keys / Values / Entries ──────────────────────────────────
console.log(Object.keys(user)); // ["name", "age", "role"]
console.log(Object.values(user)); // ["Alice", 28, "admin"]
console.log(Object.entries(user)); // [["name","Alice"], ["age",28], ...]

// ── Merge objects with Object.assign ────────────────────────
const defaults = { theme: "dark", lang: "en" };
const prefs = { lang: "fr" };
const config = Object.assign({}, defaults, prefs);
console.log(config); // { theme: "dark", lang: "fr" }

// ── Freeze — make object read-only ───────────────────────────
const CONSTANTS = Object.freeze({ MAX: 100, MIN: 0 });
CONSTANTS.MAX = 999; // silently fails (no error in non-strict mode)
console.log(CONSTANTS.MAX); // 100 ← unchanged

// ── fromEntries — transform key-value pairs ──────────────────
const prices = { apple: 1.5, banana: 0.5, cherry: 3.0 };
const withTax = Object.fromEntries(
Object.entries(prices).map(([item, price]) => [item, price * 1.18])
); // { apple: 1.77, banana: 0.59, cherry: 3.54 }

// ── hasOwn (ES2022) ──────────────────────────────────────────
console.log(Object.hasOwn(user, "name")); // true
console.log(Object.hasOwn(user, "salary")); // false

Real-World Use Cases

Objects are the backbone of every real JavaScript application — from storing user data to configuring libraries and shaping API payloads:

User / Entity Model
Represent a user, product, or any domain entity with structured named fields and methods.
Configuration Object
Pass options to a function as a single object — easy to add new options without breaking existing callers.
API Request / Response
HTTP JSON payloads are objects — parse responses with JSON.parse() and send with JSON.stringify().
Lookup / Map Table
Use an object as a O(1) key-value lookup instead of looping through an array — e.g., { id: userData }.
Counting & Grouping
Accumulate counts or group records — e.g., { apple: 3, banana: 2 } — using reduce() + object.
Immutable Constants
Use Object.freeze() to create read-only configuration objects — safe against accidental mutation.
React State & Props
React component state and props are plain objects — spread for immutable updates: { ...state, count: 1 }.
Namespace / Module
Group related functions and data under a single object to avoid polluting the global scope.
⚡
Free Resource
Download our JavaScript Cheat Sheet
Objects, arrays, destructuring & all modern JS patterns — one page.
Get Sheet

Try It — Live Editor

Experiment with object creation, property access, methods, iteration, and the Object utility APIs below.

Live Editor
✎ Editor
👁 Preview

Common Patterns & Recipes

These are everyday object patterns you'll encounter and write constantly in real JavaScript projects:

JavaScript — Object Recipes
// ── Shorthand property names (ES6) ──────────────────────────
const name = "Alice", age = 28;
const user = { name, age }; // same as { name: name, age: age }

// ── Computed property keys (ES6) ────────────────────────────
const field = "score";
const result = { [field]: 92, [`${field}_2`]: 88 };
// { score: 92, score_2: 88 }

// ── Optional chaining for safe deep access ───────────────────
const city = user?.address?.city ?? "Unknown";

// ── Merge with spread (later keys win) ──────────────────────
const merged = { ...defaults, ...overrides, timestamp: Date.now() };

// ── Immutable update (React / Redux pattern) ─────────────────
const nextState = { ...state, count: state.count + 1, loading: false };

// ── keyBy — array → object for O(1) lookup ───────────────────
const keyBy = (arr, key) => arr.reduce((acc, item) => {
acc[item[key]] = item; return acc;
}, {});
const byId = keyBy(users, "id"); // { 1: {...}, 2: {...} }

// ── Count occurrences with reduce ────────────────────────────
const fruits = ["apple", "banana", "apple", "cherry"];
const counts = fruits.reduce((acc, f) => {
acc[f] = (acc[f] || 0) + 1; return acc;
}, {}); // { apple: 2, banana: 1, cherry: 1 }

// ── Pick specific keys ───────────────────────────────────────
const pick = (obj, keys) =>
Object.fromEntries(keys.map(k => [k, obj[k]]));
pick(user, ["name", "email"]); // { name: "...", email: "..." }

// ── Omit specific keys ───────────────────────────────────────
const omit = (obj, ...keys) => {
const copy = { ...obj };
keys.forEach(k => delete copy[k]);
return copy;
};
omit(user, "password", "token"); // safe user without sensitive fields
Quick Check
Which statement is true about const obj = { a: 1 }; obj.a = 2;?
Quick Check
Given const a = { v: 1 }; const b = a; b.v = 99;, what is a.v?
Quick Check
Which method returns an array of [key, value] pairs from an object?
Chapter Summary
  • An object is a collection of key: value pairs. Keys are strings (or Symbols); values can be any JS type, including functions and other objects.
  • The object literal { } is the most common creation method. Also available: new Object() and Object.create(proto).
  • Access properties with dot notation (obj.key) for known identifiers, or bracket notation (obj["key"]) for dynamic/special-character keys.
  • Properties can be added, updated, and deleted at any time. const prevents re-assigning the variable — not mutating the object.
  • A method is a function stored as a property. Use ES6 shorthand syntax and this to access sibling properties. Never use arrow functions as methods.
  • Iterate with Object.keys(), Object.values(), or Object.entries(). Combine with for...of, map(), reduce(), or destructuring.
  • Objects are reference types. Assigning an object to a new variable copies the reference, not the data. Use { ...obj } or structuredClone(obj) to clone.
  • Useful utilities: Object.freeze() for immutability, Object.assign() for merging, Object.fromEntries() for converting arrays back to objects.

Rate Us on Google

4.8 / 5
Enjoying this tutorial?
Your 5-star review helps other learners discover our free tutorials and encourages us to keep creating quality content.
80+ reviews
Write a Google Review
Join WhatsApp Channel