JavaScript object methods are simple ways to handle data inside objects. An object can hold many values, and methods give direct access to those values.
Table of Content
Understand the Methods in JavaScript Object
A method is a function that lives inside an object. It acts on the data of that object and can return useful results.
The syntax has a function placed inside an object with a name. That function then becomes a method.
Here is an example:
let user = {
name: "John",
greet: function() {
return "Hello " + this.name;
}
};The method greet uses this.name to read the value of the key inside the same object.
JavaScript connects the keyword this to the current object. The code inside runs with the object values when you call the method.
The Object.keys() takes all keys from an object and gives them as an array.Object.values() does the same but returns the values.
let car = { brand: "Ford", year: 2021 };
console.log(Object.keys(car)); // ["brand","year"]
console.log(Object.values(car)); // ["Ford",2021]These two methods allow you to see what the object holds without manual loops.
Object.assign() and Cloning Objects
You can use Object.assign() to copy data from one object to another. It can help when you need a clone of an object.
let base = { a: 1, b: 2 };
let copy = Object.assign({}, base);
console.log(copy); // { a:1, b:2 }The method joins values from the source into a target, and hence it helps in clone tasks.
Object.entries() for Iteration
This method returns key and value pairs inside arrays. You can then use loops like for...of to run through them.
let data = { x: 10, y: 20 };
for (let [key, value] of Object.entries(data)) {
console.log(key + ":" + value);
}This way you can deal with both parts of the object in one pass.
Object.freeze() and Object.seal()
The Object.freeze() blocks changes to the object. Object.seal() allows updates of old values but does not allow new keys. Both methods help to control object safety in code.
For example:
// Example with Object.freeze()
const user1 = { name: "Ali", age: 25 };
Object.freeze(user1);
user1.age = 30; // No change
user1.city = "Riyadh"; // No new property
console.log(user1); // { name: "Ali", age: 25 }
// Example with Object.seal()
const user2 = { name: "Sara", age: 20 };
Object.seal(user2);
user2.age = 22; // Value updated
user2.city = "Jeddah"; // No new property
console.log(user2); // { name: "Sara", age: 22 }
freezestops both updates and new keys.sealallows updates but blocks new keys.
Create Custom Object Methods
You can also make your own method inside an object. A custom method can do any action you need with that object.
let bank = {
balance: 1000,
deposit: function(amount) {
this.balance = this.balance + amount;
}
};
bank.deposit(500);
console.log(bank.balance); // 1500The method acts like a rule inside the object and keeps track of its data.
Examples
Count Keys in Object:
let fruit = { apple: 5, orange: 10, banana: 7 };
let count = Object.keys(fruit).length;
console.log("Total keys: " + count);This example counts all keys inside the object with Object.keys().length. It shows how you can find the number of keys with one step instead of loops.
Merge Objects with Object.assign():
let a = { id: 1, name: "Sam" };
let b = { age: 25, city: "Paris" };
let result = Object.assign({}, a, b);
console.log(result);Here is two objects joined into one with Object.assign(). This method is useful when you need to combine user data and extra data into a single structure.
Freeze Object to Protect Data:
let config = { host: "localhost", port: 3000 };
Object.freeze(config);
config.port = 4000;
console.log(config.port);In this case the port stays at 3000 even after you try to set a new value. The Object.freeze() method protects the object so no one can make changes.
Loop with Object.entries():
let scores = { math: 90, english: 85, science: 92 };
for (let [subject, mark] of Object.entries(scores)) {
console.log(subject + " score is " + mark);
}This example shows how to loop through subjects and marks with Object.entries(). The loop prints each subject name with its mark in a simple, readable way.
Wrapping Up
In this article, you learned how methods in JavaScript objects work and how they can control data in many ways. Here is a quick recap:
- You saw how methods live inside objects as functions.
- You learned how to use keys and values.
- You saw how to clone and freeze. Also, understood how to seal objects.
- You built custom methods and used real examples.
FAQs
How do I useObject.keys() in Javascript?
const obj = {name: 'John', age: 30};
const keys = Object.keys(obj);
console.log(keys); // ['name', 'age']
What is the difference between Object.assign() and cloning an object?
const obj1 = {a: 1};
const obj2 = Object.assign({}, obj1); // shallow copy
// Object.assign copies properties into a new object
How can I iterate over Object.entries() in Javascript?
const obj = {x: 10, y: 20};
for (const [key, value] of Object.entries(obj)) {
console.log(key, value);
}
// Output: x 10
// y 20
How do Object.freeze() and Object.seal() differ?
const obj = {name: 'Alice'};
Object.freeze(obj); // Prevents changes entirely
Object.seal(obj); // Allows changes to values but not keys
Similar Reads
Object References in JavaScript mean that variables do not store full objects but only their references in memory. What is…
The JavaScript unshift function adds one or more elements at the start of an array. It shifts existing items to…
You have to organize your JavaScript code structure. A clean layout helps you read and fix your code. Whether you…
If you are a coder, one of your primary requirements is to have a trustworthy code- editor. A Code editor…
The ternary operator in JavaScript keeps your code short. It helps you write conditions inside one line. JavaScript lets you…
JavaScript Symbol Type gives a way to make unique values. A Symbol never matches any other value and this helps…
JavaScript Math.log() was added to help people find the natural log of a number. It solves real problems in science…
JavaScript removes unused memory blocks with garbage collection. It frees memory space so programs run without leaks. What is JavaScript…
You will learn what the JavaScript valueOf function does and how it works. It returns the primitive value of an…
The for...of loop appeared to solve the problem of complex loops over arrays and strings. It gives you a way…