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.
Object.create()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 constructor.
Produces the same result as a literal but is more verbose — rarely used today.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:
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 */ },
};
// ── 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:
obj.key
obj["key"]
obj[varName]
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)
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):
obj["newKey"] = value;
obj["key"]
undefined if the key doesn't exist. Never throws.
obj["key"] = newValue;
delete obj["key"];
undefined.
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 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:
// ── 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:
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:
// ── 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 itstructuredClone(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 |
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:
JSON.parse() and send with JSON.stringify().
{ id: userData }.{ apple: 3, banana: 2 } — using reduce() + object.
Object.freeze() to create read-only configuration
objects — safe against accidental mutation.{ ...state, count: 1 }.Try It — Live Editor
Experiment with object creation, property access, methods, iteration, and the Object utility APIs below.
Common Patterns & Recipes
These are everyday object patterns you'll encounter and write constantly in real JavaScript projects:
// ── 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
const obj = { a: 1 }; obj.a = 2;?
const a = { v: 1 }; const b = a; b.v = 99;, what is
a.v?
[key, value] pairs from an
object?- An object is a collection of
key: valuepairs. 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()andObject.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.
constprevents re-assigning the variable — not mutating the object. - A method is a function stored as a property. Use ES6 shorthand syntax and
thisto access sibling properties. Never use arrow functions as methods. - Iterate with
Object.keys(),Object.values(), orObject.entries(). Combine withfor...of,map(),reduce(), or destructuring. - Objects are reference types. Assigning an object to a new variable copies
the reference, not the data. Use
{ ...obj }orstructuredClone(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
Join Our Learning Community
Connect with thousands of learners, get daily tips, ask questions and stay updated with new tutorials.