JavaScript object methods are built-in functions that allow you to get information about objects, manipulate their properties, and control their behavior.
Main method groups:
These methods allow you to extract various information from an object without modifying it.
What it does: Returns an array of all own enumerable property names of the object.
const user = {
name: "Anna",
age: 25,
city: "New York"
};
const keys = Object.keys(user);
console.log(keys); // ["name", "age", "city"]
// Practical use — counting properties
console.log(`User has ${Object.keys(user).length} properties`);
What it does: Returns an array of all own enumerable property values of the object.
const user = {
name: "Anna",
age: 25,
city: "New York"
};
const values = Object.values(user);
console.log(values); // ["Anna", 25, "New York"]
// Practical use — searching in values
const hasAdult = Object.values(user).some(value =>
typeof value === 'number' && value >= 18
);
console.log(hasAdult); // true
What it does: Returns an array of arrays, where each inner array contains [key, value].
const user = {
name: "Anna",
age: 25,
city: "New York"
};
const entries = Object.entries(user);
console.log(entries);
// [["name", "Anna"], ["age", 25], ["city", "New York"]]
// Practical use — creating description string
const description = Object.entries(user)
.map(([key, value]) => `${key}: ${value}`)
.join(', ');
console.log(description); // "name: Anna, age: 25, city: New York"
These methods allow you to create new objects based on existing ones or merge multiple objects into one.
What it does: Copies all enumerable own properties from one or more source objects to a target object. Returns the modified target object.
const target = { a: 1 };
const source = { b: 2, c: 3 };
// Copying to existing object
Object.assign(target, source);
console.log(target); // { a: 1, b: 2, c: 3 }
// Creating new object (recommended way)
const newObj = Object.assign({}, target, source);
console.log(newObj); // { a: 1, b: 2, c: 3 }
// Practical use — merging settings
const defaultSettings = { theme: 'light', language: 'en' };
const userSettings = { theme: 'dark' };
const finalSettings = Object.assign({}, defaultSettings, userSettings);
console.log(finalSettings); // { theme: 'dark', language: 'en' }
Important: Object.assign() creates a shallow copy. Nested objects remain linked!
const original = { user: { name: 'Anna' } };
const copy = Object.assign({}, original);
copy.user.name = 'Boris';
console.log(original.user.name); // 'Boris' — original changed too!
What it does: Modern way to copy and merge objects, more readable than Object.assign().
const user = { name: 'Anna', age: 25 };
const address = { city: 'New York', street: 'Broadway' };
// Merging objects
const fullUser = { ...user, ...address };
console.log(fullUser);
// { name: 'Anna', age: 25, city: 'New York', street: 'Broadway' }
// Updating properties
const updatedUser = { ...user, age: 26, email: 'anna@mail.com' };
console.log(updatedUser);
// { name: 'Anna', age: 26, email: 'anna@mail.com' }
What it does: Creates a new object with the specified prototype and properties.
// Creating object with prototype
const personPrototype = {
greet() {
return `Hello, I'm ${this.name}`;
}
};
const user = Object.create(personPrototype);
user.name = 'Anna';
user.age = 25;
console.log(user.greet()); // 'Hello, I'm Anna'
// Creating object without prototype (clean dictionary)
const cleanObj = Object.create(null);
cleanObj.data = 'value';
// cleanObj doesn't have toString, hasOwnProperty, etc.
These methods help determine if an object has certain properties and how to access them safely.
What it does: Checks if the object has an own property with the specified name. Modern and safe alternative to hasOwnProperty().
const user = { name: 'Anna', age: 25 };
console.log(Object.hasOwn(user, 'name')); // true
console.log(Object.hasOwn(user, 'toString')); // false (inherited)
console.log(Object.hasOwn(user, 'email')); // false (doesn't exist)
// Practical use — safe checking before access
function getUserInfo(user, field) {
if (Object.hasOwn(user, field)) {
return user[field];
}
return 'Field not found';
}
What it does: Checks for the presence of a property in the object, including inherited properties.
const user = { name: 'Anna' };
console.log('name' in user); // true (own property)
console.log('toString' in user); // true (inherited)
console.log('email' in user); // false (doesn't exist)
// Difference between in and Object.hasOwn()
if ('toString' in user) {
console.log('toString exists'); // will execute
}
if (Object.hasOwn(user, 'toString')) {
console.log('toString is own property'); // will NOT execute
}
These methods allow you to control how objects can be modified.
What it does: Makes an object completely immutable — you cannot add, delete, or modify properties.
const config = { api: 'https://api.com', version: '1.0' };
Object.freeze(config);
// These operations won't work (will throw error in strict mode)
config.api = 'https://new-api.com'; // won't change
config.timeout = 5000; // won't be added
delete config.version; // won't be deleted
console.log(config); // { api: 'https://api.com', version: '1.0' }
// Checking if frozen
console.log(Object.isFrozen(config)); // true
What it does: Prevents adding and removing properties, but allows modifying existing ones.
const user = { name: 'Anna', age: 25 };
Object.seal(user);
// Can modify existing properties
user.name = 'Boris'; // ✅ works
user.age = 30; // ✅ works
// Cannot add or remove
user.email = 'test@mail.com'; // ❌ won't be added
delete user.age; // ❌ won't be deleted
console.log(Object.isSealed(user)); // true
function createConfig(defaultConfig, userConfig) {
// Safe merging of settings
const config = { ...defaultConfig, ...userConfig };
// Check required fields
const requiredFields = ['apiUrl', 'appName'];
const missing = requiredFields.filter(field => !Object.hasOwn(config, field));
if (missing.length > 0) {
throw new Error(`Missing required fields: ${missing.join(', ')}`);
}
// Freeze config for protection
return Object.freeze(config);
}
// Usage
const defaultConfig = { theme: 'light', apiUrl: 'https://api.com' };
const userConfig = { theme: 'dark', appName: 'MyApp' };
const finalConfig = createConfig(defaultConfig, userConfig);
function sanitizeUser(userData) {
// Allowed fields
const allowedFields = ['name', 'email', 'age'];
const sanitized = {};
// Copy only allowed fields
allowedFields.forEach(field => {
if (Object.hasOwn(userData, field)) {
sanitized[field] = userData[field];
}
});
return sanitized;
}
const userData = {
name: 'Anna',
email: 'anna@mail.com',
age: 25,
password: 'secret123', // will be removed
isAdmin: true // will be removed
};
const clean = sanitizeUser(userData);
console.log(clean); // { name: 'Anna', email: 'anna@mail.com', age: 25 }
const obj = { a: 1 };
const copy1 = Object.assign({}, obj);
const copy2 = { ...obj };
copy1.a = 2;
obj.b = 3;
console.log(obj);
console.log(copy1);
console.log(copy2);
const obj = { x: 1 };
Object.freeze(obj);
obj.x = 2;
obj.y = 3;
console.log(obj);
const nested = { a: { b: 1 } };
Object.freeze(nested);
nested.a.b = 2;
console.log(nested.a.b);
// 1. Use const for objects
const config = { apiUrl: '...' };
// 2. Use destructuring
const { name, age } = user;
// 3. Use Object.hasOwn() instead of hasOwnProperty()
if (Object.hasOwn(obj, 'property')) { /* ... */ }
// 4. Create objects without prototype for dictionaries
const dict = Object.create(null);
// 5. Use Object.assign() or spread for shallow copying
const copy = { ...original };
// 6. Use Object.freeze() for immutable objects
const constants = Object.freeze({ PI: 3.14159 });
// ❌ Modifying Object.prototype
Object.prototype.newMethod = function() {}; // Pollutes global scope
// ❌ Using for...in without hasOwnProperty check
for (const key in obj) {
console.log(obj[key]); // May include inherited properties
}
// ❌ Direct hasOwnProperty access
obj.hasOwnProperty('prop'); // May not work if overridden
// ❌ Mutating argument objects
function updateUser(user) {
user.lastLogin = new Date(); // Modifies original object
}
// ❌ Expecting deep copying
const original = { user: { name: 'Anna' }, items: [1, 2, 3] };
const copy = { ...original };
copy.user.name = 'Boris'; // Changes original!
// ✅ Proper deep copying
const deepCopy = JSON.parse(JSON.stringify(original)); // Simple way
// or
const deepCopy2 = structuredClone(original); // Modern way
// ❌ May give false result
if (obj.prop) { /* ... */ } // false for 0, "", false, null
// ✅ Correct ways
if (Object.hasOwn(obj, 'prop')) { /* ... */ }
if ('prop' in obj) { /* ... */ }
if (obj.prop !== undefined) { /* ... */ }
Object methods are powerful tools for working with data in JavaScript:
Main categories:
Object.keys()
, Object.values()
, Object.entries()
Object.create()
, Object.assign()
, spread operatorObject.hasOwn()
, in
, hasOwnProperty()
Object.freeze()
, Object.seal()
, Object.preventExtensions()
Modern features:
Applications:
Best practices:
// Safe property work
if (Object.hasOwn(obj, 'prop')) { /* ... */ }
// Proper copying
const copy = { ...original }; // shallow
const deepCopy = structuredClone(original); // deep
// Creating immutable objects
const constants = Object.freeze({ PI: 3.14159 });
Understanding object methods is the key to effective data work in JavaScript!
Want more interview preparation articles? Subscribe to EasyAdvice, bookmark the site and level up every day 💪