Creating Objects
Creating Objects
Object Literal
const person = {
name: 'John',
age: 30,
greet() {
return `Hello, ${this.name}`;
}
};
Constructor Function
function Person(name, age) {
this.name = name;
this.age = age;
this.greet = function() {
return `Hello, ${this.name}`;
};
}
const john = new Person('John', 30);
Object.create
const proto = {
greet() {
return `Hello, ${this.name}`;
}
};
const person = Object.create(proto);
person.name = 'John';
Class Syntax
class Person {
constructor(name, age) {
this.name = name;
this.age = age;
}
greet() {
return `Hello, ${this.name}`;
}
}
const john = new Person('John', 30);
Computed Property Names
const key = 'name';
const person = {
[key]: 'John',
['age']: 30,
[`get${key.charAt(0).toUpperCase() + key.slice(1)}()`]() {
return this[key];
}
};
Shorthand Properties
const name = 'John';
const age = 30;
// Long
const person = { name: name, age: age };
// Shorthand
const person = { name, age };
Object Methods
Object Methods
Method Definition
const calculator = {
value: 0,
add(n) {
this.value += n;
return this;
},
subtract(n) {
this.value -= n;
return this;
},
result() {
return this.value;
}
};
// Method chaining
calculator.add(5).subtract(2).result(); // 3
this in Methods
const person = {
name: 'John',
greet() {
console.log(this.name); // "John"
}
};
person.greet(); // this is person
Getters and Setters
const person = {
firstName: 'John',
lastName: 'Doe',
get fullName() {
return `${this.firstName} ${this.lastName}`;
},
set fullName(value) {
const [first, last] = value.split(' ');
this.firstName = first;
this.lastName = last;
}
};
console.log(person.fullName); // "John Doe" (getter)
person.fullName = 'Jane Smith'; // setter
console.log(person.firstName); // "Jane"
Computed Methods
const methods = {
double: (x) => x * 2,
triple: (x) => x * 3
};
const operation = 'double';
methods[operation](5); // 10
Object.assign
const target = { a: 1 };
const source1 = { b: 2 };
const source2 = { c: 3 };
Object.assign(target, source1, source2);
console.log(target); // { a: 1, b: 2, c: 3 }
Spread Operator
const original = { a: 1, b: 2 };
const copy = { ...original };
const merged = { ...original, c: 3 };
console.log(merged); // { a: 1, b: 2, c: 3 }
Object Manipulation
Object Manipulation
Object.keys
const person = { name: 'John', age: 30 };
Object.keys(person); // ['name', 'age']
Object.values
Object.values(person); // ['John', 30]
Object.entries
Object.entries(person); // [['name', 'John'], ['age', 30]]
// Use with destructuring
for (const [key, value] of Object.entries(person)) {
console.log(`${key}: ${value}`);
}
Object.fromEntries
const entries = [['name', 'John'], ['age', 30]];
Object.fromEntries(entries); // { name: 'John', age: 30 }
hasOwnProperty
const person = { name: 'John' };
person.hasOwnProperty('name'); // true
person.hasOwnProperty('toString'); // false
// Better: use 'in' operator
'name' in person; // true
'toString' in person; // true (inherited)
Delete Operator
const person = { name: 'John', age: 30 };
delete person.age;
console.log(person); // { name: 'John' }
Spread vs Object.assign
// Object.assign (mutates target)
const target = { a: 1 };
Object.assign(target, { b: 2 });
// Spread (creates new object)
const original = { a: 1 };
const copy = { ...original, b: 2 };
Deep Copy
// Shallow copy
const shallow = { ...original };
// Deep copy
const deep = JSON.parse(JSON.stringify(original));
// Modern deep copy
const deep = structuredClone(original);
Object.freeze
const frozen = Object.freeze({ name: 'John' });
frozen.name = 'Jane'; // Silently fails (or throws in strict)
console.log(frozen.name); // "John"
Object.seal
const sealed = Object.seal({ name: 'John' });
sealed.name = 'Jane'; // Can modify existing
sealed.age = 30; // Cannot add new
console.log(sealed); // { name: 'Jane' }
Practice Problems
Create a reusable React component implementing Objects. Include proper state management and accessibility.
Solution
// Production-ready component with:
// - Proper TypeScript types
// - Accessibility (ARIA)
// - Error boundaries
// - Loading states
// - Memoization where neededWrite unit and integration tests for Objects using React Testing Library.
Solution
// Test coverage:
// 1. Rendering tests
// 2. Interaction tests
// 3. Edge case tests
// 4. Accessibility testsOptimize Objects for performance. Consider memoization, code splitting, and bundle size.
Solution
// Optimization techniques:
// 1. React.memo / useMemo / useCallback
// 2. Code splitting with lazy()
// 3. Virtual scrolling for lists
// 4. Image lazy loading
// 5. Bundle analysisQuiz
1. What does Object.keys() return?
2. What is the difference between Object.assign and spread?
3. What does Object.freeze() do?
4. What is a getter in an object?
5. How do you create a deep copy of an object?
Flashcards
Question
What is the difference between Object.assign and spread?
Click to reveal answer
Answer
Object.assign mutates the target. Spread creates a new object without mutation.
Question
What does Object.keys() return?
Click to reveal answer
Answer
An array of the object's own enumerable property names.
Question
What is a getter?
Click to reveal answer
Answer
A method that is invoked when accessing a property, allowing computed property values.
Question
How do you freeze an object?
Click to reveal answer
Answer
Object.freeze() makes an object immutable - properties can't be added, removed, or modified.
Question
What is shorthand property syntax?
Click to reveal answer
Answer
When variable name matches property name: { name, age } instead of { name: name, age: age }.
Revision Notes
Key Takeaways
- 1.Objects store key-value pairs
- 2.Object.keys/values/entries iterate properties
- 3.Spread creates shallow copies
- 4.Getters/setters allow computed properties
- 5.Object.freeze makes objects immutable
Interview Tips
- •Know how to create and manipulate objects
- •Understand Object.keys vs Object.entries
- •Be able to implement getters and setters
- •Know the difference between shallow and deep copy
Cheat Sheet
Objects Cheat Sheet
Creating Objects
const obj = { key: value };
const obj = new Object();
const obj = Object.create(proto);
class MyClass { constructor() {} }
Object Methods
Object.keys(obj) // ['key1', 'key2']
Object.values(obj) // ['val1', 'val2']
Object.entries(obj) // [['key1', 'val1']]
Object.assign(target, ...sources)
Object.freeze(obj)
Object.seal(obj)
Spread Operator
const copy = { ...original };
const merged = { ...obj1, ...obj2 };
Getters/Setters
const obj = {
get prop() { return this._prop; },
set prop(value) { this._prop = value; }
};