JavaScript

coding learning websites codepractice

JS Basics

JS Variables & Operators

JS Data Types & Conversion

JS Numbers & Math

JS Strings

JS Dates

JS Arrays

JS Control Flow

JS Loops & Iteration

JS Functions

JS Objects

JS Classes & Modules

JS Async Programming

JS Advanced

JS HTML DOM

JS BOM (Browser Object Model)

JS Web APIs

JS AJAX

JS JSON

JS Graphics & Charts

JavaScript Object Methods


In JavaScript, object methods are functions that are stored as properties inside objects. Methods allow objects to perform operations on their own data or provide reusable functionality related to that object. For example, a calculator object might have methods like add() or multiply() to perform calculations using its data.

Understanding object methods is critical in JavaScript because they allow developers to structure code logically, reuse functions, and interact with object properties safely. In addition to user-defined methods, JavaScript provides several built-in object methods to query, manipulate, or transform objects efficiently.

Creating Object Methods

1. Function Expression as Method

A method can be assigned to an object property using a function expression:

const calculator = {
  add: function(a, b) {
    return a + b;
  }
};

console.log(calculator.add(5, 3)); // 8

Here, add is a property whose value is a function. You call it using calculator.add().

2. ES6 Short Method Syntax

ES6 introduced a cleaner way to define methods inside objects:

const calculator = {
  subtract(a, b) {
    return a - b;
  }
};

console.log(calculator.subtract(10, 4)); // 6

This syntax is more concise and widely used in modern JavaScript.

3. Using this Keyword

Inside an object method, this refers to the object itself. This allows methods to access other properties dynamically:

const person = {
  firstName: "John",
  lastName: "Doe",
  fullName() {
    return this.firstName + " " + this.lastName;
  }
};

console.log(person.fullName()); // John Doe

Note: this is bound to the object calling the method. If the method is extracted into a variable, this may refer to undefined in strict mode.

Built-in Object Methods

JavaScript provides a wide range of built-in object methods. Let’s explore the most important ones in detail.

1. Object.keys()

Returns an array of property names (keys) of an object:

const person = { name: "Alice", age: 25 };
console.log(Object.keys(person)); // ["name", "age"]

Tip: Only enumerable properties are returned.

2. Object.values()

Returns an array of property values:

console.log(Object.values(person)); // ["Alice", 25]

Useful for iterating over values without caring about the keys.

3. Object.entries()

Returns an array of [key, value] pairs:

console.log(Object.entries(person));
/*
[
  ["name", "Alice"],
  ["age", 25]
]
*/

Can be combined with for...of to iterate cleanly:

for (const [key, value] of Object.entries(person)) {
  console.log(key, "=", value);
}

4. Object.assign()

Copies properties from one or more source objects to a target object.

const target = { a: 1 };
const source = { b: 2, c: 3 };
Object.assign(target, source);
console.log(target); // { a: 1, b: 2, c: 3 }

Tip: This is useful for merging objects or creating shallow copies.

5. Object.freeze()

Prevents adding, deleting, or modifying properties:

const user = { name: "Sam" };
Object.freeze(user);
user.name = "Tom"; // Ignored
console.log(user.name); // Sam

Frozen objects are immutable, useful when you want to protect configuration objects.

6. Object.seal()

Prevents adding or deleting properties, but allows modification:

const car = { brand: "Toyota" };
Object.seal(car);
car.brand = "Honda";  // Allowed
car.model = "Camry";  // Ignored
console.log(car); // { brand: "Honda" }

Sealing is less strict than freezing but still protects object structure.

7. Object.hasOwn()

Checks if an object directly contains a property (not inherited):

const student = { name: "Rahul" };
console.log(Object.hasOwn(student, "name")); // true
console.log(Object.hasOwn(student, "age"));  // false

Available in ES2022 and later. Before that, hasOwnProperty() was used.

8. Object.getOwnPropertyNames()

Returns all property names, including non-enumerable ones:

const obj = Object.create({}, { a: { value: 10, enumerable: false } });
console.log(Object.getOwnPropertyNames(obj)); // ["a"]

9. Object.getOwnPropertyDescriptor()

Returns detailed property attributes:

const obj = { name: "Sam" };
console.log(Object.getOwnPropertyDescriptor(obj, "name"));
/*
{
  value: "Sam",
  writable: true,
  enumerable: true,
  configurable: true
}
*/

10. Object.fromEntries()

Converts an array of [key, value] pairs into an object:

const entries = [["name", "Alice"], ["age", 25]];
const obj = Object.fromEntries(entries);
console.log(obj); // { name: "Alice", age: 25 }

Useful for transforming data received from APIs or form inputs.

Calling Object Methods Dynamically

You can call a method dynamically if the property name is stored in a variable:

const person = {
  greet() { return "Hello!"; }
};

const methodName = "greet";
console.log(person[methodName]()); // Hello!

Notes and Tips

  • Methods should use this to interact with object properties.

  • Built-in object methods often return new arrays or objects and do not mutate the original unless specified.

  • Object.freeze() and Object.seal() are useful for preventing accidental modifications in large codebases.

  • Dynamic method calls allow flexible code patterns, especially when working with configuration objects or APIs.

Summary of the Tutorial

  • Object methods are functions stored as object properties.

  • Methods can use this to access the object itself.

  • JavaScript provides many built-in methods for object manipulation:

    • Access: Object.keys(), Object.values(), Object.entries()

    • Modification: Object.assign()

    • Protection: Object.freeze(), Object.seal()

    • Inspection: Object.getOwnPropertyDescriptor(), Object.getOwnPropertyNames(), Object.hasOwn()

    • Conversion: Object.fromEntries()

  • Understanding these methods is essential for working with complex objects, APIs, and data structures efficiently.


Practice Questions

  1. Create an object calculator with methods add(a, b) and subtract(a, b). Call both methods and log the results.

  2. Use this in a method: Create an object person with firstName and lastName properties and a method fullName() that returns the full name. Log the full name.

  3. Use Object.keys(): Create an object book with properties title, author, and year. Log all the keys of the object.

  4. Use Object.values(): Log all the values of the book object.

  5. Use Object.entries(): Loop through the book object using Object.entries() and log each key–value pair in the format key: value.

  6. Use Object.assign(): Merge two objects obj1 = {a: 1} and obj2 = {b: 2, c: 3} into a new object and log the result.

  7. Use Object.freeze(): Freeze an object user = {name: "Sam", age: 25}. Try changing the name property and log the object to see the effect.

  8. Use Object.seal(): Seal an object car = {brand: "Toyota"}. Try adding a new property model and modifying brand. Log the final object.

  9. Use Object.getOwnPropertyDescriptor(): Check the descriptor of the brand property in the car object created above. Log its attributes.

  10. Use Object.fromEntries(): Convert an array [["name", "Alice"], ["age", 25]] into an object and log the object.


JavaScript

online coding class codepractice

JS Basics

JS Variables & Operators

JS Data Types & Conversion

JS Numbers & Math

JS Strings

JS Dates

JS Arrays

JS Control Flow

JS Loops & Iteration

JS Functions

JS Objects

JS Classes & Modules

JS Async Programming

JS Advanced

JS HTML DOM

JS BOM (Browser Object Model)

JS Web APIs

JS AJAX

JS JSON

JS Graphics & Charts

Go Back Top