Object Methods
Tags: javascript, beginners, codenewbie, webdev
Published: 2020-08-01 19:53:58

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 <b>properties and methods.</b>

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. 

🛑 <b>Remember: </b>
👉 All objects in JavaScript descend from the parent Object constructor. Object has many useful <b>built-in methods</b> 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`, <b>Object methods are used directly on the Object constructor,</b> and use the object instance as a <b>parameter.</b> This is known as a<b> static method.</b>

👉 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 <b>functions stored as object properties.</b> Now let’s see how you can access these object methods in JavaScript.

###👉 <b> How to access object Methods? </b>
You can access the object methods using the following syntax:

```js

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 the` FullName()` method of a person object:

```js
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 <b>global Object constructor</b> are:
🔻
+ Object.create()
+ Object.keys()
+ Object.freeze()
+ Object.values()
+ Object.entries()
+ Object.seal()
+ Object.getPrototypeOf()

### <b> Object.create()</b> 🤔

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

```js
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`.

### <b>Object.keys()</b> 🤔

👉 The `object.keys` function is used to pick only keys or property labels of objects and<b> returns an array.</b>

```js
let keys = Object.keys(person);
console.log(keys);
// [ 'name', 'age' ]
```

### <b>Object.freeze()</b> 🤔

👉 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.

```js
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:

```js
let values = Object.values(person);
console.log(values);
```

```js
// 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.

### <b> Object.values()</b> 🤔

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

```js
// 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.

### <b> Object.entries()</b> 🤔

🛑 `Object.entries()` creates a nested array of the key/value pairs of an object.

```js
// 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);
```

```js
Output
[
    ["name", "Linux"]
    ["version", 7.04]
    ["license", "Open Source"]
]
```
👉 Once we have the <b>key/value pair arrays</b> , we can use the `forEach()` method to <b>loop</b> through and work with the results.

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

    console.log(`${key}: ${value}`);
});
```
```js
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.

### <b>Object.assign()</b> 🤔
👉 `Object.assign()` is used to copy values from one object to another.

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

```javascript
// 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.

```js
// 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](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Spread_syntax#Spread_in_object_literals) in object literals is also known as shallow-cloning.

### <b>Object.seal()</b> 🤔

👉 `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.
```js
// 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.

### <b> Object.getPrototypeOf()</b>

👉  `Object.getPrototypeOf()` is used to get the internal hidden <b>[[Prototype]] of an object,</b> also accessible through the `__proto__ `property.

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

```js

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.

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

//Output
true
```

🤔 This method can be useful to get more information about an <b>object</b> 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,<b> iterate through the keys and/or values of an object,</b> and `freeze` or `seal` an object.

These are some of the different types of Methods. 


Happy Coding & Have Fun ! 🤖 🤩 🚀