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 }
freeze
stops both updates and new keys.seal
allows 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); // 1500
The 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
Math.atan() function in JavaScript helps you to solve math problems in your code. It turns a number into an angle.…
JavaScript added Math.cbrt to solve cube roots. Before that, developers used custom code or Math.pow with 1/3. It works with…
You will face hoisting early when you write JavaScript. It affects how your code runs, and it may confuse you…
You use loops in JavaScript to repeat code without copying it many times. This helps when you handle lots of…
Math.random() gives a number between 0 and 1 in JavaScript. It helps create random values for colors or other data.…
Code mistakes used to slip by without a warning. That made bugs hard to trace and fix. JavaScript "use strict"…
The Math.acos function finds the angle in radians from a cosine value in JavaScript. It gives a value between 0…
JavaScript switch statement checks many values without long chains. It appeared to replace stacked conditions that slow you down. Understand…
JavaScript gives you several ways to round numbers, but not all of them round the same way. If you want…
The current essay is devoted to the basic principles and introduction of JavaScript. This language no longer needs to be…