11 JavaScript Object Methods You Must Know About

11 JavaScript Object Methods You Must Know About

ยท

6 min read

In JavaScript, Objects are a special datatype that allows you to hold data in a form of 'Key-value' Pairs. Here the key is an object property that references the 'value' stored within that object. To access the value from the object you can either specify the property name through dot notation or specify the property name in string form inside square brackets.

Objects are extremely useful in JavaScript. You would want some sort of datatype where you can easily store some data and then retrieve it via the property name. Objects let you exactly do that.

But what's the real power of Objects is the many operations you can perform on them. Thus enabling the developer to write more effective code!

But do you know all the useful Object methods that JavaScript has? We will be looking at 11 In-built Object methods that will make performing various types of operations Objects possible!

Quick Glance at all the Object methods

  1. Object.assign()

  2. Object.entries()

  3. Object.fromEntries()

  4. Object.keys()

  5. Object.freeze()

  6. Object.isFrozen()

  7. Object.seal()

  8. Object.isSealed()

  9. Object.values()

  10. Object.prototype.valueOf()

  11. Object.prototype.toString()

Object.assign()

This method will copy all the properties of one, or more than one Object and return a new Object with all the properties and values combined

Let's say you have 2 Objects in a file and you want to merge both of them and return a new one. Object.assign() lets you exactly do that.

Example!

const batsman = {
    century: 1,
    runs: 43
};

const bowler = {
    hattricks: 3,
    wickets: 4
};

const cricketer = Object.assign({}, batsman, bowler);
console.log(cricketer);
/*
Output:
{ century: 1, runs: 43, hattricks: 3, wickets: 4 }
*/
  • First parameter: Takes a target object in which to copy over all the other Objects' entries

  • Rest of the parameters: Objects whose entries will be copied

  • Returns => A new Object

Object.entries()

This method returns an array of arrays, each containing the property and value of the Object.

Each key-value pair in an Object is called an 'Entry'. Sometimes you may want to access both the key (property) and value of an Object. Object.entries() will return an array of all the properties and values that you defined in it before.

Example!

const matchInfo = {
    hasStarted: true,
    playerCount: 22,
    hostId: 1234567890
};
console.log(Object.entries(matchInfo));
/*
Output:
[
  [ 'hasStarted', true ],
  [ 'playerCount', 22 ],
  [ 'hostId', 1234567890 ]
]
*/

Here, the properties will be printed in string form. It takes only one argument and that is the Object.

Object.fromEntries()

This method will make and return a new Object from an Array.

Let's say you have an array of key-value pairs and you want to convert them all into an Object. Object.fromEntries() will let you do it!

Example!

const inventoryArray = [
    ['mangos', 34],
    ['oranges', 22],
    ['banana', 10]
]

const inventory = Object.fromEntries(inventoryArray)
console.log(inventory);
/*
{ mangos: 34, oranges: 22, banana: 10 }
*/

It takes an Array as its argument. The array must have a collection of arrays that have 2 elements, the first must be a string and the second one can be of any type. The first element will be the property and the second one will be the value.

Object.keys()

We saw above that Object.entries() will give you an array of key-value pairs defined in that Object. But what if you only want the keys? Object.keys() Enables you to do it!

const inventory = { mangos: 34, oranges: 22, banana: 10 }
console.log(Object.keys(inventory));
// Output: [ 'mangos', 'oranges', 'banana' ]

Object.values()

Similarly, if you want the values only from the Object, then you can use Object.values() method to get an array of all values defined in it!

Both Object.keys() and Object.values() take only one parameter which is an Object.

const inventory = { mangos: 34, oranges: 22, banana: 10 }
console.log(Object.values(inventory));
// Output: [ 34, 22, 10 ]

Object.freeze()

This method freezes an Object. An object that is frozen cannot be modified or extended with new property value pairs. This method will return a new frozen Object.

Use case for freezing objects

When you are sure that the Object's properties and values will not be changed as well as new ones won't be added, you can completely freeze that Object to prevent unexpected mutations to it. This is useful when you want to define some Enums in pure JavaScript.

Example!

const Status = Object.freeze({
    OK: 200,
    REDIRECT: 300,
    CLIENT_ERROR: 400,
    SERVER_ERROR: 500,
});

Status.NEW_STATUS = 600
Status.OK = 201
// This will throw an error in strict mode, otherwise it will be ignored

console.log(Status);
// Output: { OK: 200, REDIRECT: 300, CLIENT_ERROR: 400, SERVER_ERROR: 500 }

console.log(Object.isFrozen(Status));
// Output: true

Have you noticed that the OK still has 200 as value and there is no NEW_STATUS property on Status Object? It is because we have frozen it thus we can't modify to add anything new to the Object.

Here we have defined an Object as if they were Enum types.

Object.isFrozen()

As the name implies this method will check if the given Object is frozen or not, as specified in the above Example.

Object.seal()

This method seals an Object. An Object that is sealed cannot have more property values added, cannot delete already defined properties and cannot configure them as well. However, you can still modify the values of these properties as before.

The difference between Object.freeze and Object.seal is that freeze will completely prevent you from doing anything from the object. While sealing an object will still allow you to modify the existing defined properties of the object.

const Player = Object.seal({
    name: "Samir",
    points: 100,
    participant: true
});

Player.level = 12
Player.points += 10

console.log(Player);
// Output: { name: 'Samir', points: 110, participant: true }

console.log(Object.isSealed(Player));
/// Output: true

As you can see, it let us change the points property of the Player, but won't add level property in it. Trying to add a new property or deleting an existing defines property will throw out an Error in strict mode, otherwise, it will be ignored.

Object.isSealed()

As the name implies this method will check if the given Object or not, as specified in the above Example.

Object.prototype.valueOf()

valuesOf() is supposed to return a Primitive type value for an Object which can be useful for various operations such as equality checks.

By default, the valueOf() returns a new copy of the Object. This method is abstract and is supposed to be overridden by other Objects to return something useful.

const user = {
    name: "SAMIR",
    id: 1234567890
}
console.log(user.valueOf());

Object.prototype.valueOf = function () {
    return this.id
}

console.log(user.valueOf());        // Output: 1234567890
console.log(user == 1234567890);    // Output: true
console.log(user + 1);              // Output: 1234567891

Object.prototype.toString()

toString() is supposed to return a string for an Object which can be useful for various operations.

By default, the toString() returns [object Object]. This method is abstract and is supposed to be overridden by other Objects to return something useful.

const user = {
    name: "SAMIR",
    id: 1234567890
}

console.log(user.toString());

Object.prototype.toString = function () {
    return `${this.name}-${this.id}`
}

console.log(user.toString());   // Output: SAMIR-1234567890
console.log(`${user}`);         // Output: SAMIR-1234567890

The End!

That is all you need to know about the various methods and operations you can perform on JavaScript Objects. Try to use them to your advantage!

If you have made it to the end of this article, Thank you so much for reading this! ๐Ÿ’

ย