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()
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();
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());
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' ]
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
β 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);
// 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"}
β π€ 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"]
π 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);
Output
[
["name", "Linux"]
["version", 7.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: Linux
version: 7.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()
.
// 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"}
π 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);
β 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: "*******"}
π 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: Ζ, β¦]
π 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. 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)