Object.keys() returns an array of names of all enumerable properties of an object. Convenient for iterating keys, checking property count, or converting object to other data structures.
const user = { name: 'John', age: 25 };
const keys = Object.keys(user);
console.log(keys); // ['name', 'age']Object.keys() is a method to get all keys (property names) of an object. It’s very simple and often used when working with objects.
Returns array of strings — names of all own enumerable properties:
const user = { name: 'John', age: 25 };
const keys = Object.keys(user);
console.log(keys); // ['name', 'age']const user = { name: 'John', age: 25, city: 'Moscow' };
const count = Object.keys(user).length;
console.log(count); // 3const config = { theme: 'dark', lang: 'en' };
Object.keys(config).forEach(key => {
console.log(key, config[key]); // theme dark, lang en
});const obj = { name: 'John' };
// Doesn't include inherited methods like toString
console.log(Object.keys(obj)); // ['name']const obj = { name: 'John' };
// Hide property
Object.defineProperty(obj, 'hidden', {
value: 'secret',
enumerable: false
});
console.log(Object.keys(obj)); // ['name'] - hidden not visibleconst user = { name: 'John', age: 25 };
// ❌ Complex way
for (let key in user) {
if (user.hasOwnProperty(key)) {
console.log(key);
}
}
// ✅ Simple way
Object.keys(user).forEach(key => {
console.log(key);
});const obj = { a: 1, b: 2 };
// Check if object has properties
if (Object.keys(obj).length > 0) {
console.log('Object is not empty');
}// ❌ Thinking we get values
const obj = { a: 1, b: 2 };
const result = Object.keys(obj);
console.log(result); // ['a', 'b'] - keys, not values!
// ✅ For values use Object.values()
const values = Object.values(obj);
console.log(values); // [1, 2]// ❌ Trying to use with primitives
Object.keys(42); // Error!
// ✅ Only with objects
Object.keys({ value: 42 }); // ['value']Object.keys() is convenient when you need to work only with object keys. This is simpler than for…in and doesn’t require inheritance checks.
Want more articles to prepare for interviews? Subscribe to EasyAdvice, bookmark the site and improve yourself every day 💪