Skip to main content

Objects & Object Methods


Creating Objects

// Object literal (most common)
const person = {
name: "Reet",
age: 25,
city: "Rajkot",
greet() {
return `Hi, I'm ${this.name}`;
}
};

// Constructor function (old-style)
function Person(name, age) {
this.name = name;
this.age = age;
}
const p1 = new Person("Alice", 30);

// Object.create()
const proto = { greet() { return "Hello"; } };
const obj = Object.create(proto);

Accessing Properties

const car = { make: "Toyota", model: "Camry", year: 2023 };

// Dot notation
car.make; // "Toyota"

// Bracket notation (use when key is dynamic or has spaces)
car["model"]; // "Camry"
const key = "year";
car[key]; // 2023

// Optional chaining
car?.engine?.horsepower; // undefined (no error)

Object Destructuring

const user = { name: "Reet", age: 25, city: "Rajkot" };

// Basic destructuring
const { name, age } = user;

// Rename while destructuring
const { name: userName, age: userAge } = user;

// Default values
const { name: n, role = "developer" } = user;
// role = "developer" (user.role is undefined)

// Nested destructuring
const data = { user: { profile: { bio: "Dev" } } };
const { user: { profile: { bio } } } = data;
// bio = "Dev"

// In function parameters
function greet({ name, age }) {
return `${name} is ${age} years old`;
}

// Rest in destructuring
const { name: nm, ...rest } = user;
// nm = "Reet", rest = { age: 25, city: "Rajkot" }

Object Methods

const obj = { a: 1, b: 2, c: 3 };

// Get keys, values, entries
Object.keys(obj); // ["a", "b", "c"]
Object.values(obj); // [1, 2, 3]
Object.entries(obj); // [["a",1],["b",2],["c",3]]

// Create from entries
Object.fromEntries([["a",1],["b",2]]); // {a:1, b:2}

// Freeze (prevent any modification)
const frozen = Object.freeze({ x: 1 });
frozen.x = 99; // silently fails (or Error in strict mode)
frozen.x; // still 1

// Assign (merge objects, MODIFIES target)
const target = { a: 1 };
Object.assign(target, { b: 2 }, { c: 3 });
// target is now { a:1, b:2, c:3 }

// Shallow copy with spread
const original = { a: 1, b: { c: 2 } };
const copy = { ...original };
copy.a = 99; // doesn't affect original.a
copy.b.c = 99; // DOES affect original.b.c (shallow!)

// Deep clone
const deepCopy = JSON.parse(JSON.stringify(original)); // limited (no functions/dates)
const deepCopy2 = structuredClone(original); // ES2022, recommended

// Check property existence
"a" in obj; // true
obj.hasOwnProperty("a"); // true

Computed Property Names

const prefix = "user";
const obj = {
[`${prefix}Name`]: "Reet",
[`${prefix}Age`]: 25,
};
// { userName: "Reet", userAge: 25 }

Shorthand Properties and Methods

const name = "Reet";
const age = 25;

// Property shorthand
const person = { name, age }; // same as { name: name, age: age }

// Method shorthand (ES6)
const calc = {
add(a, b) { return a + b; },
};

Property Descriptors

const obj = {};
Object.defineProperty(obj, "id", {
value: 42,
writable: false, // cannot reassign
enumerable: true, // shows in for...in, Object.keys()
configurable: false // cannot delete or redefine
});

Getters and Setters

const person = {
_firstName: "Reet",
_lastName: "Dev",
get fullName() {
return `${this._firstName} ${this._lastName}`;
},
set fullName(value) {
[this._firstName, this._lastName] = value.split(" ");
}
};

person.fullName; // "Reet Dev" (get)
person.fullName = "Alice Smith"; // (set)
person._firstName; // "Alice"

MCQ — Objects

Q1: Which method returns an array of [key, value] pairs from an object?

A) Object.keys() B) Object.values() C) Object.entries()D) Object.pairs()

Answer: C

Q2: What does Object.freeze() do?

A) Creates a deep copy B) Prevents properties from being added, modified, or deleted ✅ C) Makes the object immutable recursively D) Converts the object to a string

Answer: B — Note: freeze() is SHALLOW. Nested objects can still be mutated.

Q3: What is the output?
const a = { x: 1 };
const b = { ...a };
b.x = 99;
console.log(a.x);

A) 99 B) 1C) undefined D) Error

Answer: B — Spread creates a shallow copy. Primitive values are independent.

Q4: How do you check if a property exists in an object?

A) obj.has("prop") B) "prop" in objC) obj.contains("prop") D) obj["prop"] !== null

Answer: B — Also obj.hasOwnProperty("prop") for own properties only.

Q5: What is structuredClone() used for?

A) Shallow copying an object B) Deep cloning an object ✅ C) Freezing an object D) Comparing two objects

Answer: B

Q6: What is the issue with JSON.parse(JSON.stringify(obj)) for deep cloning?

A) No issues B) It doesn't work at all C) It loses functions, undefined, Date objects, and circular references ✅ D) It's too slow

Answer: C

Q7: What does const { a, ...rest } = { a:1, b:2, c:3 } give?

A) a = 1, rest = undefined B) a = 1, rest = { b:2, c:3 }C) a = {a:1}, rest = {b:2,c:3} D) SyntaxError

Answer: B

Q8: Can you add properties to a const object?

A) No, const prevents all modification B) Yes, const only prevents reassignment of the variable ✅ C) Only if using Object.assign

Answer: B — Use Object.freeze() to prevent modification.