-
Hajipur, Bihar, 844101
Hajipur, Bihar, 844101
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 Functions
Function Definitions
Function Parameters
Function Invocation
Function Call
Function Apply
Function Bind
Function Closures
JS Arrow Function
JS Objects
JS Objects
JS Object Properties
JS Object Methods
JS Object Display
JS Object Constructors
Object Definitions
Object Get / Set
Object Prototypes
Object Protection
JS Classes & Modules
JS Async Programming
JS Advanced
JS Destructuring
JS Bitwise
JS RegExp
JS Precedence
JS Errors
JS Scope
JS Hoisting
JS Strict Mode
JS this Keyword
JS HTML DOM
DOM Intro
DOM Methods
DOM Document
DOM Elements
DOM HTML
DOM Forms
DOM CSS
DOM Animations
DOM Events
DOM Event Listener
DOM Navigation
DOM Nodes
DOM Collections
DOM Node Lists
JS BOM (Browser Object Model)
JS Web APIs
Web API Intro
Web Validation API
Web History API
Web Storage API
Web Worker API
Web Fetch API
Web Geolocation API
JS AJAX
AJAX Intro
AJAX XMLHttp
AJAX Request
AJAX Response
AJAX XML File
AJAX PHP
AJAX ASP
AJAX Database
AJAX Applications
AJAX Examples
JS JSON
JSON Intro
JSON Syntax
JSON vs XML
JSON Data Types
JSON Parse
JSON Stringify
JSON Objects
JSON Arrays
JSON Server
JSON PHP
JSON HTML
JSON JSONP
JS Graphics & Charts
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.
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()
.
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.
this
KeywordInside 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 toundefined
in strict mode.
JavaScript provides a wide range of built-in object methods. Let’s explore the most important ones in detail.
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.
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.
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);
}
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.
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.
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.
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.
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"]
Object.getOwnPropertyDescriptor()
Returns detailed property attributes:
const obj = { name: "Sam" };
console.log(Object.getOwnPropertyDescriptor(obj, "name"));
/*
{
value: "Sam",
writable: true,
enumerable: true,
configurable: true
}
*/
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.
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!
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.
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.
Create an object calculator
with methods add(a, b)
and subtract(a, b)
. Call both methods and log the results.
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.
Use Object.keys()
: Create an object book
with properties title
, author
, and year
. Log all the keys of the object.
Use Object.values()
: Log all the values of the book
object.
Use Object.entries()
: Loop through the book
object using Object.entries()
and log each key–value pair in the format key: value
.
Use Object.assign()
: Merge two objects obj1 = {a: 1}
and obj2 = {b: 2, c: 3}
into a new object and log the result.
Use Object.freeze()
: Freeze an object user = {name: "Sam", age: 25}
. Try changing the name
property and log the object to see the effect.
Use Object.seal()
: Seal an object car = {brand: "Toyota"}
. Try adding a new property model
and modifying brand
. Log the final object.
Use Object.getOwnPropertyDescriptor()
: Check the descriptor of the brand
property in the car
object created above. Log its attributes.
Use Object.fromEntries()
: Convert an array [["name", "Alice"], ["age", 25]]
into an object and log the object.
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 Functions
Function Definitions
Function Parameters
Function Invocation
Function Call
Function Apply
Function Bind
Function Closures
JS Arrow Function
JS Objects
JS Objects
JS Object Properties
JS Object Methods
JS Object Display
JS Object Constructors
Object Definitions
Object Get / Set
Object Prototypes
Object Protection
JS Classes & Modules
JS Async Programming
JS Advanced
JS Destructuring
JS Bitwise
JS RegExp
JS Precedence
JS Errors
JS Scope
JS Hoisting
JS Strict Mode
JS this Keyword
JS HTML DOM
DOM Intro
DOM Methods
DOM Document
DOM Elements
DOM HTML
DOM Forms
DOM CSS
DOM Animations
DOM Events
DOM Event Listener
DOM Navigation
DOM Nodes
DOM Collections
DOM Node Lists
JS BOM (Browser Object Model)
JS Web APIs
Web API Intro
Web Validation API
Web History API
Web Storage API
Web Worker API
Web Fetch API
Web Geolocation API
JS AJAX
AJAX Intro
AJAX XMLHttp
AJAX Request
AJAX Response
AJAX XML File
AJAX PHP
AJAX ASP
AJAX Database
AJAX Applications
AJAX Examples
JS JSON
JSON Intro
JSON Syntax
JSON vs XML
JSON Data Types
JSON Parse
JSON Stringify
JSON Objects
JSON Arrays
JSON Server
JSON PHP
JSON HTML
JSON JSONP
JS Graphics & Charts