JavaScript Object Methods

JavaScript objects have built-in methods that allow you to work with object properties and methods effectively. These methods are essential for manipulating and querying objects in JavaScript.

1. Object.keys()

The Object.keys() method returns an array of a given object's own enumerable property names.


const person = {
    name: "Alice",
    age: 25
};

console.log(Object.keys(person)); // ["name", "age"]

            

2. Object.values()

The Object.values() method returns an array of a given object's own enumerable property values.


const person = {
    name: "Alice",
    age: 25
};

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

            

3. Object.entries()

The Object.entries() method returns an array of a given object's own enumerable string-keyed property [key, value] pairs.


const person = {
    name: "Alice",
    age: 25
};

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

            

4. Object.assign()

The Object.assign() method copies the values of all enumerable own properties from one or more source objects to a target object. It returns the 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 }

            

5. Object.freeze()

The Object.freeze() method freezes an object. A frozen object can no longer be modified: new properties cannot be added, existing properties cannot be removed or changed, and the object's prototype cannot be changed.


const person = {
    name: "Alice",
    age: 25
};

Object.freeze(person);
person.age = 30; // This will not change the age property
console.log(person.age); // 25

            

6. Object.seal()

The Object.seal() method seals an object. A sealed object cannot have new properties added to it, and its existing properties cannot be removed, but they can still be modified.


const person = {
    name: "Alice",
    age: 25
};

Object.seal(person);
delete person.age; // This will not delete the age property
person.age = 30; // This will change the age property
console.log(person.age); // 30