Following are two ways of accessing & manipulating Object :-
Static. We cannot use a variable. The engine interprets the text after the dot literally.Example:
let key = "status";
let data = {
[key]: "Active", // Creates { status: "Active" }
["user_" + 101]: 123, // Creates { user_101: 123 }
};This is the most fundamental architectural Limitation of standard JavaScript Objects.
In a standard Object, all keys are Strings. If we try to use any other data type as a key, the engine will Implicitly convert it to a string before storage.
Consider this scenario where we try to use Objects as keys:
let user = { id: 1 };
let admin = { id: 2 };
let dictionary = {};
dictionary[user] = "User Data";
dictionary[admin] = "Admin Data";
console.log(dictionary[user]); // Output: "Admin Data"The Mechanism:
The Limitation: Standard Objects cannot handle unique object references as keys. They only see the string representation. (To use actual objects as keys, we use the Map data structure).
for...in LoopLegacy method. Iterates over enumerable properties (including inherited ones).
const user = { name: "Alice", role: "Admin" };
for (let key in user) {
console.log(key, user[key]);
}
// Output: "name" "Alice", "role" "Admin"Object.keys()Returns an array of the object's own keys.
const user = { name: "Alice", role: "Admin" };
// Returns: ["name", "role"]
Object.keys(user).forEach((key) => {
console.log(key);
});Object.values()Returns an array of the object's own values.
const user = { name: "Alice", role: "Admin" };
// Returns: ["Alice", "Admin"]
Object.values(user).forEach((value) => {
console.log(value);
});Object.entries()Returns an array of [key, value] pairs. Useful for destructuring.
const user = { name: "Alice", role: "Admin" };
// Returns: [ ["name", "Alice"], ["role", "Admin"] ]
Object.entries(user).forEach(([key, value]) => {
console.log(`${key}: ${value}`);
});| Feature | Dot Notation | Bracket Notation |
|---|---|---|
| Syntax | obj.key | obj["key"] |
| Key Type | Literal Identifier | Expression (String/Symbol) |
| Variables | No | Yes |