Tutorial

How To Use Object Methods in JavaScript

Updated on August 26, 2021
English
How To Use Object Methods in JavaScript

Introduction

Objects in JavaScript are collections of key/value pairs. The values can consist of properties and methods, and may contain all other JavaScript data types, such as strings, numbers, and Booleans.

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.

This tutorial will go over important built-in object methods, with each section below dealing with a specific method and providing an example of use.

Prerequisites

In order to get the most out of this tutorial, you should be familiar with creating, modifying, and working with objects, which you can review in the “Understanding Objects in JavaScript” article.

For additional guidance on JavaScript in general, you can review our How To Code in JavaScript series.

Object.create()

The Object.create() method is used to create a new object and link it to the prototype of an existing object.

We can create a job object instance, and extend it to a more specific object.

// Initialize an object with properties and methods
const job = {
    position: 'cashier',
    type: 'hourly',
    isAvailable: true,
    showDetails() {
        const accepting = this.isAvailable ? 'is accepting applications' : "is not currently accepting applications";

        console.log(`The ${this.position} position is ${this.type} and ${accepting}.`);
    }
};

// Use Object.create to pass properties
const barista = Object.create(job);

barista.position = "barista";
barista.showDetails();
Output
The barista position is hourly and is accepting applications.

The barista object now has one property — position — but all the other properties and methods from job are available through the prototype. Object.create() is useful for keeping code DRY by minimizing duplication.

Object.keys()

Object.keys() creates an array containing the keys of an object.

We can create an object and print the array of keys.

// Initialize an object
const employees = {
	boss: 'Michael',
	secretary: 'Pam',
	sales: 'Jim',
	accountant: 'Oscar'
};

// Get the keys of the object
const keys = Object.keys(employees);

console.log(keys);
Output
["boss", "secretary", "sales", "accountant"]

As Object.keys converts your object’s keys into an array of keys, the forEach() array method can be used to iterate through the keys and values.

// Iterate through the keys
Object.keys(employees).forEach(key => {
    let value = employees[key];

	 console.log(`${key}: ${value}`);
});
Output
boss: Michael secretary: Pam sales: Jim accountant: Oscar

Object.keys is also useful for checking the length of the converted array using the length property.

// Get the length of the keys
const length = Object.keys(employees).length;

console.log(length);
Output
4

Using the length property, we were able to count the 4 properties of employees.

Object.values()

Object.values() creates an array containing the values of an object.

// Initialize an object
const session = {
    id: 1,
    time: `26-July-2018`,
    device: 'mobile',
    browser: 'Chrome'
};

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

console.log(values);
Output
[1, "26-July-2018", "mobile", "Chrome"]

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: 'Ubuntu',
    version: 18.04,
    license: 'Open Source'
};

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

console.log(entries);
Output
[ ["name", "Ubuntu"] ["version", 18.04] ["license", "Open Source"] ]

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}`);
});
Output
name: Ubuntu version: 18.04 license: Open Source

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().

// Initialize an object
const name = {
    firstName: 'Philip',
    lastName: 'Fry'
};

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

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

console.log(character);
Output
{firstName: "Philip", lastName: "Fry", job: "Delivery Boy", employer: "Planet Express"}

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: 'Philip',
    lastName: 'Fry'
};

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

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

console.log(character);
Output
{firstName: "Philip", lastName: "Fry", job: "Delivery Boy", employer: "Planet Express"}

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

Object.freeze()

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

// Initialize an object
const user = {
	username: 'AzureDiamond',
	password: 'hunter2'
};

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

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

console.log(newUser);
Output
{username: "AzureDiamond", password: "hunter2"}

In the example above, we tried to override the password hunter2 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.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: 'AzureDiamond',
	password: 'hunter2'
};

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

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

console.log(newUser);
Output
{username: "AzureDiamond", password: "*******"}

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 = ['Ron', 'April', 'Andy', 'Leslie'];

Object.getPrototypeOf(employees);
Output
[constructor: ƒ, concat: ƒ, find: ƒ, findIndex: ƒ, pop: ƒ, …]

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

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.

Conclusion

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.

If you need to review JavaScript objects you can read “Understanding Objects in JavaScript.” If you would like to familiarize yourself with the prototype chain, you can take a look at “Understanding Prototypes and Inheritance in JavaScript.”

Thanks for learning with the DigitalOcean Community. Check out our offerings for compute, storage, networking, and managed databases.

Learn more about our products


Tutorial Series: How To Code in JavaScript

JavaScript is a high-level, object-based, dynamic scripting language popular as a tool for making webpages interactive.

About the authors


Still looking for an answer?

Ask a questionSearch for more help

Was this helpful?
 
4 Comments


This textbox defaults to using Markdown to format your answer.

You can type !ref in this text area to quickly search our full set of tutorials, documentation & marketplace offerings and insert the link!

Thanks - I found this article helpful!

P.S. What theme are you using for your code editor?

Great article! It’s always good when developers teach javascript from how it naturally operates.

One thing to point out about Object.assign is that now character is really a pointer to name.

~$ node --version
v10.8.0

~$ node
> // Initialize an object
undefined
> const name = {
...     firstName: 'Philip',
...     lastName: 'Fry'
... };
undefined
>
> // Initialize another object
undefined
> const details = {
...     job: 'Delivery Boy',
...     employer: 'Planet Express'
... };
undefined
>
> // Merge the objects
undefined
> const character = Object.assign(name, details);
undefined
>
> console.log(character);
{ firstName: 'Philip',
  lastName: 'Fry',
  job: 'Delivery Boy',
  employer: 'Planet Express' }
undefined
> console.log(name);
{ firstName: 'Philip',
  lastName: 'Fry',
  job: 'Delivery Boy',
  employer: 'Planet Express' }
undefined
> console.log(details);
{ job: 'Delivery Boy', employer: 'Planet Express' }
undefined
> name.foo = '1'
'1'
> character
{ firstName: 'Philip',
  lastName: 'Fry',
  job: 'Delivery Boy',
  employer: 'Planet Express',
  foo: '1' }

Awesome! Thanks

Try DigitalOcean for free

Click below to sign up and get $200 of credit to try our products over 60 days!

Sign up

Join the Tech Talk
Success! Thank you! Please check your email for further details.

Please complete your information!

Become a contributor for community

Get paid to write technical tutorials and select a tech-focused charity to receive a matching donation.

DigitalOcean Documentation

Full documentation for every DigitalOcean product.

Resources for startups and SMBs

The Wave has everything you need to know about building a business, from raising funding to marketing your product.

Get our newsletter

Stay up to date by signing up for DigitalOcean’s Infrastructure as a Newsletter.

New accounts only. By submitting your email you agree to our Privacy Policy

The developer cloud

Scale up as you grow — whether you're running one virtual machine or ten thousand.

Get started for free

Sign up and get $200 in credit for your first 60 days with DigitalOcean.*

*This promotional offer applies to new accounts only.