Object
Object
1. What is an Object?
1. In JavaScript, an object is a collection of key-value pairs,
where keys are strings (or Symbols), and values can be of any
data type, including functions.
2. Object Constructor :
5. Computed Properties.
6. Property names can be dynamic:
let fruit = "apple";
let bag = { [fruit]: 5 };
console.log(bag.apple); // 5
2. Comparison by Reference.
14. Two objects are equal (== or ===) only if they reference the
same object.
15. Two independent objects with the same properties are not
equal.
16. E.g :-
let a = {};
let b = a;
console.log(a == b); // true (same reference)
console.log(a === b); //true
let c = {};
console.log(a == c); // false (different objects)
3. const Objects Can be Modified.
17. Declaring an object with "const' means the reference cannot
change, but the object’s properties can still be modified.
18. E.g :-
const user = {
name: "John"
};
user.name = "Pete";
alert(user.name); // Pete
alert(clone.name); // John
alert(clone.age); // 30
alert(clone.name); // John
alert(clone.age); // 30
5. Deep Cloning (for Nested Objects)
25. Object.assign() and spread syntax do not deeply clone objects
(nested objects are copied by reference).
26. Use structuredClone() or libraries like Lodash (_.cloneDeep)
for deep cloning.
27. E.g :-
let user = {
name: "John",
sizes: { height: 182, width: 50 }
};
1. Object Methods.
28. Objects in JavaScript can have functions as properties, called
methods.
29. Methods define actions that an object can perform.
30. Eg :-
let user = {
name: "John",
age: 30,
sayHi: function() {
alert("Hello!");
}
};
user.sayHi(); // Hello!
31. Methods can also be assigned from pre-declared functions:
let user = {
name: "John",
age: 30,
sayHi: function() {
alert("Hello!");
}
};
user.sayHi(); // Hello!
2. Method Shorthand.
32. JavaScript allows a shorter syntax for defining methods:
let user = {
sayHi() { // Same as sayHi: function() { ... }
alert("Hello");
}
};
3. this in Methods.
34. Methods often need to access object properties.
35. The keyword this refers to the object calling the method.
36. E.g:-
let user = {
name: "John",
sayHi() {
alert(this.name);
}
};
user.sayHi(); // John
37. Using this ensures the correct reference, even if the object is
reassigned:
let user = {
name: "John",
sayHi() {
alert(this.name);
}
};
function sayHi() {
alert(this.name);
}
user.f = sayHi;
admin.f = sayHi;
user.f(); // John
admin.f(); // Admin
alert(user.name); // Jack
alert(user.isAdmin); // false
Checking "new.target"
51. We can check if a function was called with new:
function User() {
alert(new.target);
}
User(); // undefined
new User(); // function User { ... }
this.name = "John";
1. Introduction.
55. Optional chaining (?.) allows safe access to nested object
properties even if an intermediate property doesn’t exist. This
helps prevent runtime errors caused by accessing undefined or null
properties.
56. Note: Old browsers may require polyfills to support this
feature.
2. The "Non-Existing Property" Problem
57. When trying to access deeply nested properties of an object,
we may encounter errors if any intermediate property is undefined.
58. E.g :-
let user = {}; // user object with no "address" property
console.log(user.address.street); // Error!
Since user.address is undefined, accessing street causes an error.
5. Short-Circuiting Behavior.
63. The optional chaining operator short-circuits the evaluation if
the left-side operand is null or undefined.
64. E.g :-
let user = null;
let x = 0;
console.log(x); // 0
Since user is null, the method sayHi is not executed, and x is not
incremented.
console.log(user1?.[key]); // "John"
console.log(user2?.[key]); // undefined
Global Symbols :-
84. To create a global symbol, use Symbol.for(key), which
ensures the symbol is stored in a registry:
let id1 = Symbol.for("id");
let id2 = Symbol.for("id");
console.log(id1 === id2); // true
System Symbols :-
JavaScript provides built-in system symbols, such as:
85. Symbol.iterator (for iterables)
86. Symbol.toPrimitive (for type conversion)
Example of Symbol.toPrimitive:
let obj = {
[Symbol.toPrimitive](hint) {
return hint === "string" ? "Object as string" : 100;
}
};
console.log(obj + 10); // 110
* Object.fromEntries :-
87. Object.fromEntries() is a JavaScript method that converts an
array of key-value pairs into an object.
88. It is the inverse of Object.entries(), which converts an object
into an array of key-value pairs.
89. Syntax :- Object.fromEntries(iterable)
90. iterable: An array (or any iterable object) containing key-
value pairs.
91. E.g :-
const entries = [['name', 'Alice'], ['age', 25], ['city', 'New York']];
const obj = Object.fromEntries(entries);
console.log(obj);
// Output: { name: 'Alice', age: 25, city: 'New York' }
* Object.entries(obj) :-
92. The Object.entries(obj) method returns an array of key-value
pairs from an object.
93. Syntax :- Object.entries(obj);
94. obj – The object to convert into an array.
95. Returns an array of [key, value] pairs
96. E.g :-
const user = { name: "Alice", age: 25, country: "USA" };
console.log(Object.entries(user));
/* Output:
[
["name", "Alice"],
["age", 25],
["country", "USA"]
]
*/
* Object.keys(obj) :-
97. The Object.keys(obj) method returns an array of an object's
keys (property names).
98. Syntax :- Object.keys(obj);
99. obj – The object whose keys (property names) you want to
retrieve.
100. Returns an array of strings representing the object's keys.
101. E.g :-
const user = { name: "Alice", age: 25, country: "USA" };
console.log(Object.keys(user));
// Output: [ 'name', 'age', 'country' ]
// Iterating Over an Object Using Object.keys()
const person = { name: "John", age: 30, city: "New York" };
Object.keys(person).forEach(key => {
console.log(`${key}: ${person[key]}`);
});
/* Output:
name: John
age: 30
city: New York
*/
* Object.values(obj) :-
102. The Object.values(obj) method returns an array of an
object's values (property values).
103. Syntax :- Object.values(obj);
104. obj – The object whose values you want to retrieve.
105. Returns an array of values.
106. E.g :-
const user = { name: "Alice", age: 25, country: "USA" };
console.log(Object.values(user));
// Output: [ 'Alice', 25, 'USA' ]
// Iterating Over an Object Using Object.values()
const product = { id: 101, name: "Laptop", price: 75000 };
Object.values(product).forEach(value => {
console.log(value);
});
/* Output:
101
Laptop
75000
*/
111. Syntax:-
Object.getOwnPropertyDescriptor(obj, propertyName)
112. E.g :-
console.log(Object.getOwnPropertyDescriptor(user, "name"));
/*
value: "John",
writable: true,
enumerable: true,
configurable: true
*/
114. Syntax :-
115. E.g:-
value: "John",
});
4. Flag Behaviors :-
116. writable: false → Property value can't be changed.
E.g :-
120. Syntax:-
Object.defineProperties(obj, {
prop1: descriptor1,
prop2: descriptor2
});
121. E.g :-
Object.defineProperties(user, {
});
b) Object.seal() :-
130. Object.seal() is a method in JavaScript that prevents adding
or removing properties from an object, but still allows modifying
the existing properties.
131. Syntax:- Object.seal(obj)
132. obj: The object you want to seal.
133. Returns: The sealed object.
134. E.g: -
const user = { name: 'Alice', age: 30 };
c) Object.freeze() :-
137. Object.freeze() is a method in JavaScript that prevents
adding, deleting, or modifying properties in an object. It makes
the object completely immutable.
138. Syntax:- Object.freeze(obj)
139. obj: The object you want to seal.
140. Returns: The frozen object.
141. E.g: -
const person = { name: 'Alice', age: 25 };
// Freeze the object
Object.freeze(person);
Object.freeze(obj);
Object.values(obj).forEach(value => {
deepFreeze(value);
});
console.log(data.user.name); // 'John'