DEV Community

Cover image for Object Methods

Object Methods

Methods are actions that can be performed on objects. Object properties can be both primitive values, other objects, and functions.
πŸ›‘ An object method is an object property containing a function definition. JavaScript objects are containers for named values, called properties and methods.

JavaScript objects are collections of key or value pairs. The values consist of properties and methods. Also, it contains other JavaScript data types, such as strings, numbers, and Booleans.

πŸ›‘ Remember:
πŸ‘‰ All objects in JavaScript descend from the parent Object constructor. Object has many useful built-in methods we can use and access to make working with individual objects straightforward. Unlike Array prototype methods like sort()and reverse() that are used on the array instance, Object methods are used directly on the Object constructor, and use the object instance as a parameter. This is known as a static method.

πŸ‘‰ In this article, we will discuss about the different JavaScript methods in the following sequence:

  • πŸ‘‰ What are JavaScript Methods?
  • πŸ‘‰ How to access Object Methods?
  • πŸ‘‰ Different Types of JavaScript Methods

πŸš€ What are JavaScript Methods?

πŸ‘‰ JavaScript methods are actions that can be performed on objects. A JavaScript method is a property that contains a function definition. For example:

Property Value
FirstName Irene
LastName Smith
Age 25
EyeColor Brown
Height 167

πŸ‘‰ These methods are nothing but functions stored as object properties. Now let’s see how you can access these object methods in JavaScript.

πŸ‘‰ How to access object Methods?

You can access the object methods using the following syntax:


objectName.methodName()
Enter fullscreen mode Exit fullscreen mode

Here, you have to describe the FullName() as a method of the Person object, and FullName as a property. The fullName property works as a function when it is invoked with (). Here is an example of how to accesses theFullName() method of a person object:

Name = person.FullName();
Enter fullscreen mode Exit fullscreen mode

This is how you can access the object method. Now, there are different types of Methods. So, we will discuss these methods in detail.

πŸ‘‰ Different Types of JavaScript Methods

The different types of JavaScript Methods that are available in global Object constructor are:
πŸ”»

  • Object.create()
  • Object.keys()
  • Object.freeze()
  • Object.values()
  • Object.entries()
  • Object.seal()
  • Object.getPrototypeOf()

Object.create() πŸ€”

You can create object with Object.create() function. This has an additional flexibility that lets you choose the prototype of your new object.

let createObj = Object.create(obj);
console.log(createObj); //{}
createObj.name = "Danny";
console.log(createObj.speak());
Enter fullscreen mode Exit fullscreen mode

In the above example, obj is the prototype from which createdObj is created. Also, it can use the properties of the prototype due to inheritance. Thus, you can use speak() method without declaring that in createdObj.

Object.keys() πŸ€”

πŸ‘‰ The object.keys function is used to pick only keys or property labels of objects and returns an array.

let keys = Object.keys(person);
console.log(keys);
// [ 'name', 'age' ]
Enter fullscreen mode Exit fullscreen mode

Object.freeze() πŸ€”

πŸ‘‰ The freeze function is used to freeze the object for any changes in key or values. It doesn’t throw any error unless you are in strict mode. But there will be no effect of value change on your object.

πŸ‘‰ Object.freeze() prevents modification to properties and values of an object, and prevents properties from being added or removed from an object.

let frozenObject = Object.freeze(person);
frozenObject.name = "Irene";
console.log(frozenObject);
Object.values
Enter fullscreen mode Exit fullscreen mode

❗ This function is used to select only values of objects and returns an array in the following way:

let values = Object.values(person);
console.log(values);
Enter fullscreen mode Exit fullscreen mode
// Initialize an object
const user = {
    username: 'FullMoon',
    password: 'meteor6'
};

// Freeze the object
const newUser = Object.freeze(user);

newUser.password = '*******';
newUser.active = true;

console.log(newUser);

//Output:
{username: "FullMoon", password: "meteor6"}
Enter fullscreen mode Exit fullscreen mode

❗ πŸ€” In the example above, we tried to override the password meteor6 with *******, but the password property remained the same. We also tried to add a new property, active, but it was not added.

πŸ‘‰ Object.isFrozen() is available to determine whether an object has been frozen or not, and returns a Boolean.

Object.values() πŸ€”

πŸ›‘ Object.values() creates an array containing the values of an object.

// Initialize an object
const session = {
    id: 1,
    time: `6-June-2019`,
    device: 'mobile',
    browser: 'Chrome'
};

// Get all values of the object
const values = Object.values(session);

console.log(values);

// Output
// [1, "6-June-2019", "mobile", "Chrome"]
Enter fullscreen mode Exit fullscreen mode

πŸ‘‰ Object.keys() and Object.values() allow you to return the data from an object.

Object.entries() πŸ€”

πŸ›‘ Object.entries() creates a nested array of the key/value pairs of an object.

// Initialize an object
const operatingSystem = {
    name: 'Linux',
    version: 7.04,
    license: 'Open Source'
};

// Get the object key/value pairs
const entries = Object.entries(operatingSystem);

console.log(entries);
Enter fullscreen mode Exit fullscreen mode
Output
[
    ["name", "Linux"]
    ["version", 7.04]
    ["license", "Open Source"]
]
Enter fullscreen mode Exit fullscreen mode

πŸ‘‰ Once we have the key/value pair arrays , we can use the forEach() method to loop through and work with the results.

// Loop through the results
entries.forEach(entry => {
    let key = entry[0];
    let value = entry[1];

    console.log(`${key}: ${value}`);
});
Enter fullscreen mode Exit fullscreen mode
Output
name: Linux
version: 7.04
license: Open Source
Enter fullscreen mode Exit fullscreen mode

πŸ‘‰ The Object.entries() method will only return the object instance’s own properties, and not any properties that may be inherited through its prototype.

Object.assign() πŸ€”

πŸ‘‰ Object.assign() is used to copy values from one object to another.

We can create two objects, and merge them with Object.assign().

// Initialise an object
const name = {
    firstName: 'Carlson',
    lastName: 'Fleming'
};

// Initialise another object
const details = {
    job: 'Delivery Boy',
    employer: 'Durst Express'
};

// Merge the objects
const character = Object.assign(name, details);

console.log(character);
//Output
// {firstName: "Carlson", lastName: "Fleming", job: "Delivery Boy", employer: "Planet Express"}
Enter fullscreen mode Exit fullscreen mode

πŸ‘‰ It is also possible to use the spread operator (...) to accomplish the same task. In the code below, we’ll modify how we declare character through merging the name and details objects.

// Initialize an object
const name = {
    firstName: 'Carlton',
    lastName: 'Flemming'
};

// Initialize another object
const details = {
    job: 'Delivery Boy',
    employer: 'Durst Express'
};

// Merge the object with the spread operator
const character = {...name, ...details}

console.log(character);

Enter fullscreen mode Exit fullscreen mode

❗ This spread syntax in object literals is also known as shallow-cloning.

Object.seal() πŸ€”

πŸ‘‰ Object.seal() prevents new properties from being added to an object, but allows the modification of existing properties. This method is similar to Object.freeze(). Refresh your console before implementing the code below to avoid an error.

// Initialize an object
const user = {
    username: 'FullMoon',
    password: 'meteor6'
};

// Seal the object
const newUser = Object.seal(user);

newUser.password = '*******';
newUser.active = true;

console.log(newUser);

//Output
// {username: "FullMoon", password: "*******"}
Enter fullscreen mode Exit fullscreen mode

πŸ‘‰ The new active property was not added to the sealed object, but the password property was successfully changed.

Object.getPrototypeOf()

πŸ‘‰ Object.getPrototypeOf() is used to get the internal hidden [[Prototype]] of an object, also accessible through the __proto__property.

In this example, we can create an array, which has access to the Array prototype


const employees = ['Rene', 'Irene', 'Alene', 'Laura'];

Object.getPrototypeOf(employees);

//Output
// [constructor: Ζ’, concat: Ζ’, find: Ζ’, findIndex: Ζ’, 
pop: Ζ’, …]

Enter fullscreen mode Exit fullscreen mode

πŸ‘‰ We can see in the output that the prototype of the employees array has access to pop, find, and other Array prototype methods. We can confirm this by testing the employees prototype against Array.prototype.

Object.getPrototypeOf(employees) === Array.prototype;

//Output
true
Enter fullscreen mode Exit fullscreen mode

πŸ€” This method can be useful to get more information about an object or ensure it has access to the prototype of another object. πŸš€

πŸ€” There is also a related Object.setPrototypeOf() method that will add one prototype to another object. It is recommended that you use Object.create() instead as it is faster and more performant.

πŸ‘‰ Objects have many useful methods that help us modify, protect, and iterate through them. In this tutorial, we reviewed how to create and assign new objects, iterate through the keys and/or values of an object, and freeze or seal an object.

These are some of the different types of Methods.

Happy Coding & Have Fun ! πŸ€– 🀩 πŸš€

Top comments (0)