10 JavaScript Object Methods You Must Know

10 JavaScript Object Methods You Must Know

There are several JavaScript Object Methods available to make a developer’s life easier. In this post, I am going to show you the frequently used 10 JavaScript object methods and their real-world use cases.

List of JavaScript Object Method

  1. Object.create()
  2. Object.freeze()
  3. Object.seal()
  4. Object.preventExtensions()
  5. Object.fromEntries()
  6. Object.defineProperty() and Object.defineProperties()
  7. Object.assign()
  8. Object.keys()
  9. Object.values()
  10. Object.entries()

1. Object.create() – JavaScript Object Method

Object.create() in JavaScript creates an object from another object as its prototype. By this way of creating an object, We can use parent object methods/properties in the newly created child objects because of prototypal inheritance.

If you don’t know how prototypal inheritance works in JavaScript Object, please check out this Object ProtoTypes Tutorial

Use Object.create() method instead of normal shorthand syntax when you want to define a parent object for the new object.

const animal = {
  isAnimal: false,
  printIntroduction: function() {
    console.log(`This is ${this.name}. Is it an animal? ${this.isAnimal}`);
  }
};

const obj = Object.create(person);

obj.name = 'Lion'; // "name" is a property set on "obj", but not on "animal"
obj.isAnimal = true; // inherited properties can be overwritten

obj.printIntroduction();
// expected output: "This is Lion. Is it an animal? true"

2. Object.freeze() – JavaScript Object Method

Object.freeze() in JavaScript makes an object immutable. You can’t change/add a new entry or delete an existing entry to the frozen object. Think of Object.freeze() as a way to make an object a Constant. Anytime you would want to have a variable constant, you could have an object constant with freeze for similar reasons.

Object.freeze() real-world use cases are maintaining states in the frontend that syncs with the server. For example, if we have a permission object in our application that we get from the API response, we don’t want the developers who are using that permission object to modify/add any entries to that somewhere in the application.

You can detect whether an object is frozen or not by using Object.isFrozen(objVariable)

const obj = {
  prop: 42
};

console.log(Object.isFrozen(obj))
// expected output: false

Object.freeze(obj);

obj.prop = 33;
// Throws an error in strict mode

console.log(Object.isFrozen(obj))
// expected output: true

console.log(obj.prop);
// expected output: 42

3. Object.seal() – JavaScript Object Method

Object.seal() is similar to Object.freeze() but a sealed object can only change/update the values of the entry. We cannot add or delete the existing items.

You can detect whether an object is sealed or not by using Object.isSealed(objVariable)

const obj = {
  property1: 42
};

console.log(Object.isSealed(obj))
// expected output: false

Object.seal(object1);
obj.property1 = 33;
console.log(obj.property1);
// expected output: 33

delete obj.property1; // cannot delete when sealed
console.log(obj.property1);
// expected output: 33

console.log(Object.isSealed(obj))
// expected output: true

4. Object.preventExtensions() – JavaScript Object Method

Object.preventExtensions() method does not allow to add new entry to the object. It allows to change/update the entries and also delete the existing entries, but it will not allow adding any new entry after it has been created.

You can detect whether an object can be extended or not using Object.isExtensible() method

const object1 = {};

Object.isExtensible(empty); // true

Object.preventExtensions(object1);

Object.isExtensible(empty); // false

try {
  Object.defineProperty(object1, 'property1', {
    value: 42
  });
} catch (e) {
  console.log(e);
  // expected output: TypeError: Cannot define property property1, object is not extensible
}

5. Object.fromEntries()

Object.fromEntries() converts an array/Map of given key-value pairs into an object. For example, If your backend is PHP then you can receive the API responses as a multi-dimensional array as well.

To convert that multi-dimensional array to an object, you can use fromEntries() method.

const entries = new Map([
  ['foo', 'bar'],
  ['baz', 42]
]);

const obj = Object.fromEntries(entries);

console.log(obj);
// expected output: Object { foo: "bar", baz: 42 }

6. Object.defineProperty() and Object.defineProperties() Method

Object.defineProperty()adds new property or modifies the existing property in an object. This is actually the preferred method because you have full control over an object property and can configure the property like whether it should be writeable and enumerable etc.

By default, values added using Object.defineProperty() are immutable and not enumerable.

const object1 = {};

Object.defineProperty(object1, 'property1', {
  value: 42,
  writable: false
});

object1.property1 = 77;
// throws an error in strict mode

console.log(object1.property1);
// expected output: 42

Object.defineProperties() is like Object.defineProperty() but it creates/modifies multiple properties in one go in an object.

const object1 = {};

Object.defineProperties(object1, {
  property1: {
    value: 42,
    writable: true
  },
  property2: {}
});

console.log(object1.property1);
// expected output: 42

7. Object.assign() Method

Object.assign() method copies all the entries of the source object to a target object and is also useful to shallow copy objects. Learn how to shallow copy and deep copy objects in JavaScript.

Be careful with this one because it will not only return a copied object but also change the target object.

const target = { a: 1, b: 2 };
const source = { b: 4, c: 5 };

const returnedTarget = Object.assign(target, source);

console.log(target);
// expected output: Object { a: 1, b: 4, c: 5 }

console.log(returnedTarget);
// expected output: Object { a: 1, b: 4, c: 5 }

8. Object.keys() Method

Object.keys() method returns all the keys present inside an object as an array and will return only enumerable properties. Keys are property names of an object.

What are enumerable Properties in JavaScript Object?

Enumerable properties are those properties whose internal enumerable flag is set to true, which is the default for properties created via simple assignment or via a property initializer. Properties defined via Object.defineProperty and such are not enumerable by default. Most iteration means (such as for...in loops and Object.keys) only visit enumerable keys.

Mozilla Developer
const object1 = {
  a: 'somestring',
  b: 42,
  c: false
};

console.log(Object.keys(object1));
// expected output: Array ["a", "b", "c"]

9. Object.values() Method

Object.values() method returns all the enumerable property values of an object as an array, in the same order as in for..in loop.

The order of the returned values is the same as in the ordering of the properties in the given object.

const object1 = {
  a: 'somestring',
  b: 42,
  c: false
};

console.log(Object.values(object1));
// expected output: Array ["somestring", 42, false]

10. Object.entries() Method

Object.entries() returns both keys and values of an object as a 2-dimensional array.

const object1 = {
  a: 'somestring',
  b: 42
};

for (const [key, value] of Object.entries(object1)) {
  console.log(`${key}: ${value}`);
}

// expected output:
// "a: somestring"
// "b: 42"

Conclusion

In this list, We have covered frequently used JavaScript Object Methods. I Hope, it gave clarity about the methods. if you have used any of the above methods to solve real-world problems in your application, please share that in the comment to help other developers.