Beginner LevelJavaScript & TypeScript
How do JavaScript Object static methods (keys, values, entries, freeze, seal) work?
❓ Interview Prompt: Explain Object.keys(), Object.values(), Object.entries(), Object.freeze(), and Object.seal().
JavaScript provides static Object utility methods for reflection and immutability:
Inspection Methods:
•
`Object.keys(obj)`: Returns an array of an object's own enumerable property names (keys).
•
`Object.values(obj)`: Returns an array of an object's own enumerable property values.
•
`Object.entries(obj)`: Returns an array of
[key, value] pairs (useful for Map or for...of loops).Immutability Methods:
•
`Object.seal(obj)`: Prevents adding or deleting properties. Existing properties can still be modified.
•
`Object.freeze(obj)`: Highest protection. Prevents adding, deleting, OR modifying any properties (shallow freeze).
Code Implementation Example
javascript
const user = { name: 'Alice', role: 'admin' };
console.log(Object.keys(user)); // ['name', 'role']
console.log(Object.values(user)); // ['Alice', 'admin']
console.log(Object.entries(user));// [['name', 'Alice'], ['role', 'admin']]
// Immutability checks
const config = Object.freeze({ api: 'https://api.com' });
// config.api = 'other'; // Throws error in strict mode! (Unchanged)
const sealedObj = Object.seal({ id: 1 });
sealedObj.id = 2; // ✅ Allowed (modifying existing key)
// delete sealedObj.id; // ❌ Error (cannot delete sealed key)💡Object property extraction and shallow Object.freeze vs Object.seal protection.
🎯 Interview Key Takeaway
Object.entries converts objects into iterable tuples. Object.freeze prevents all modifications; Object.seal allows property edits but no additions/deletions.
#Objects#Reflection#Immutability#Beginner
Back to all JavaScript & TypeScript Questions→