JavaScript Notes
Learn JavaScript object methods: Object.keys, Object.assign, Object.create, custom methods, method shorthand ES6, and built-in static methods with real examples.
What are Object Methods?
An object method is a function that lives inside an object as a property. When a function is a property of an object, it's called a method. JavaScript also provides powerful static methods on the Object constructor itself.
Think of methods as the actions an entity can perform: a Car object has.start(),.stop(),.accelerate(). The data (brand, speed) is the *state*; the functions are the *behavior*.
Defining Custom Methods
Method Shorthand (ES6 — Preferred)
const calculator = {
result: 0,
add(a, b) {
this.result = a + b;
return this.result;
},
multiply(a, b) {
this.result = a * b;
return this.result;
}
};
console.log(calculator.add(10, 5));
console.log(calculator.multiply(4, 3));15 12
Function Expression in Object (Old Way)
const greeter = {
name: "WoHoTech",
greet: function() {
return `Welcome to ${this.name}!`;
}
};
console.log(greeter.greet());Welcome to WoHoTech!
Comparison: shorthand vs function expression
| Feature | Shorthand greet() {} | Function Expression greet: function() {} |
|---|---|---|
| Syntax | Cleaner, shorter | Verbose |
this binding | Same (both regular functions) | Same |
| Use as constructor | ❌ Cannot | ✅ Can (rarely needed) |
| ES version | ES6+ | ES5+ |
Built-in Static Object Methods
Object.keys() / .values() / .entries()
const laptop = { brand: "Dell", ram: "16GB", storage: "512GB" };
console.log(Object.keys(laptop));
console.log(Object.values(laptop));
console.log(Object.entries(laptop));[ 'brand', 'ram', 'storage' ] [ 'Dell', '16GB', '512GB' ] [ [ 'brand', 'Dell' ], [ 'ram', '16GB' ], [ 'storage', '512GB' ] ]
Object.assign() — Merge / Shallow Clone
const defaults = { theme: "light", lang: "en", notifications: true };
const userPrefs = { theme: "dark", lang: "hi" };
// Merge userPrefs INTO defaults copy
const finalConfig = Object.assign({}, defaults, userPrefs);
console.log(finalConfig);{ theme: 'dark', lang: 'hi', notifications: true }Merge order (left → right):
{} ← defaults ← userPrefs
(later keys override earlier ones)Object.create() — Prototype-based Object Creation
const animalMethods = {
speak() {
return `${this.name} says ${this.sound}`;
},
eat() {
return `${this.name} is eating.`;
}
};
const dog = Object.create(animalMethods);
dog.name = "Bruno";
dog.sound = "Woof";
console.log(dog.speak());
console.log(dog.eat());Bruno says Woof Bruno is eating.
Object.fromEntries() — Convert Array to Object
{ name: 'Riya', age: 22, city: 'Delhi' }
{ mango: 150, kiwi: 200 }Object.hasOwn() — Modern Property Check (ES2022)
const user = { name: "Aman", role: "admin" };
console.log(Object.hasOwn(user, "name")); // true
console.log(Object.hasOwn(user, "email")); // false
console.log(Object.hasOwn(user, "toString")); // false (prototype)true false false
✅ PreferObject.hasOwn()overobj.hasOwnProperty()— it's safer if the object has overriddenhasOwnProperty.
Object.freeze() — Immutable Object
const PI = Object.freeze({ value: 3.14159, name: "pi" });
PI.value = 9999; // silently fails (throws in strict mode)
PI.unit = "radians"; // silently fails
console.log(PI);{ value: 3.14159, name: 'pi' }Object.keys() Count — Object "Length"
const order = { id: 1001, item: "Book", qty: 3, status: "shipped" };
console.log(Object.keys(order).length); // Count properties4
Chaining Methods with Object.entries()
[ 'Charlie: 95', 'Alice: 88' ]
All Static Object Methods — Quick Reference
| Method | What it does | Returns |
|---|---|---|
Object.keys(obj) | All own enumerable keys | Array |
Object.values(obj) | All own enumerable values | Array |
Object.entries(obj) | All own [key, val] pairs | Array |
Object.fromEntries(arr) | Array of pairs → object | Object |
Object.assign(target, ...src) | Merge sources into target | Modified target |
Object.create(proto) | New object with given prototype | Object |
Object.freeze(obj) | Make fully immutable | Same object |
Object.seal(obj) | Prevent add/delete, allow modify | Same object |
Object.hasOwn(obj, key) | Check own property (ES2022) | Boolean |
Object.defineProperty(obj, k, d) | Define with descriptor | Same object |
Object.getPrototypeOf(obj) | Get prototype | Prototype object |
Common Mistakes ❌
1. Mutating the original with Object.assign
// ❌ Wrong — first argument IS the target (gets mutated)
const original = { a: 1 };
const copy = Object.assign(original, { b: 2 });
console.log(original); // { a: 1, b: 2 } — original mutated!
// ✅ Correct — use empty object as target
const safeCopy = Object.assign({}, original, { b: 2 });2. Expecting Object.freeze() to deep-freeze
3. Object method losing this context
// ❌ Wrong
const user = { name: "Neha", greet() { return `Hi ${this.name}`; } };
const fn = user.greet; // extracted from object
console.log(fn()); // "Hi undefined" — this is now global/undefined
// ✅ Correct — bind, arrow, or call with context
console.log(fn.bind(user)()); // "Hi Neha"Interview Questions 🎯
Q1. What is the difference between a method and a function? > A function is a standalone callable block. A method is a function that is a property of an object — the key difference is context (this refers to the containing object).
Q2. What does Object.assign() do and what are its limitations? > It copies own enumerable properties from source objects into a target. It performs a shallow copy — nested objects are not deep-copied, just their references are copied.
Q3. What is Object.create() and when do you use it? > Creates a new object with the specified prototype. Useful for manual prototype chain setup without using classes.
Q4. What is the difference between Object.freeze() and const? > const prevents the variable from being reassigned to a new object. Object.freeze() prevents the object's properties from being modified. They're complementary, not interchangeable.
Q5. What does Object.entries() return and how is it useful? > Returns an array of [key, value] pairs. Extremely useful for iterating with forEach/map/filter, or converting back with Object.fromEntries().
Q6. What is Object.hasOwn() and why prefer it over hasOwnProperty()? > Both check if a property exists on the object itself (not prototype). Object.hasOwn() is safer because an object could override hasOwnProperty as a property, breaking the check.
Q7. How do you create a deep clone of an object? > For simple objects: JSON.parse(JSON.stringify(obj)). For complex objects (with functions, dates, etc.): use structuredClone(obj) (ES2022) or a library like Lodash's _.cloneDeep().
Key Takeaways 🏁
- Methods are functions stored as object properties; use shorthand syntax
method() {} Object.keys/values/entries()are the workhorses for property iterationObject.assign({}, src)merges objects — always use{}as first arg to avoid mutationObject.freeze()is shallow — nested objects remain mutableObject.hasOwn()is the modern, safe way to check own propertiesObject.fromEntries()+Object.entries()enable powerful object transformation pipelines- Extracting a method from its object loses the
thisbinding — usebind()or arrow functions
Exam Focus
Revise definitions, diagrams, examples, and short-answer points for JavaScript Object Methods - Built-in Methods & Custom Methods Complete Guide.
Interview Use
Prepare one clear explanation, one practical example, and one common mistake for this JavaScript Master Course topic.
Search Terms
javascript-complete-guide, javascript master course, javascript, complete, guide, objects, object, methods
Related JavaScript Master Course Topics