JavaScript Object Methods
Tags: javascript, codenewbie, webdev, tutorial
Published: 2022-07-24 17:33:12

## Introduction

Every day we are working on real-world problems so if the implementation language is JavaScript then we must work with objects. And to work efficiently we must know the most used methods of the object. And I want to reference that information in this article is based on Mozila

## Table Of Contents
1. [create()](#create)
2. [assign()](#assign)
3. [keys()](#keys)
4. [values()](#values)
5. [entries()](#entries)
6. [fromEntries()](#fromEntries)
7. [freez() & seal()](#freez&seal)


### Object.create() <a name="create"></a>

The `object.create()` method Is used to create a new object and link I to the prototype of an existing object. It returns a new object with the specified prototype object and properties. 

``` javascript
let student = {
	name: "Abid",
	age: 23,
	display() {
		console.log("Name: ", this.name);
        }
};

let std = Object.create(Student);  // Object Creation

std.name = "Ahmed" 
std.display();  // with same properties
```

## Object.assign () <a name="assign"></a> 
The `Object.assign()` method assigns/copies enumerable and own properties from a source object to a target object. It returns the modified or new target object.  

``` javascript
const target = { a: 1, b: 2 };
const source = { c: 4, d: 5 };

// it merge the objects and return new objects
const newTarget = Object.assign(target, source); 

console.log(target);
// expected output: Object { a: 1, b: 2, c: 4, d:5 }

console.log(newTarget);
// expected output: Object { a: 1, b: 2, c: 4, d:5 }
```

As you have noticed in above example that after merging two objects it returned the result in new object, but also it changed target object itself. If we do not want to reflect out changes on existing objects then we have to use empty `{}` object as a first parameter of assign method.

``` javascript
const target = { a: 1, b: 2 };
const source = { c: 4, d: 5 };

// it merge the objects and return new objects
const newObj = Object.assign({},target, source); 

console.log(target);
// expected output: Object { a: 1, b: 2 }

console.log(newObj);
// expected output: Object { a: 1, b: 2, , c: 4, d:5  }
```


If the source and target property are the same then it overwrites the target property by the new value of source.

``` javascript
const target = { a: 1, b: 2 };
const source = { b: 4, c: 5 };

const newObj = Object.assign({}, target, source);

console.log(target);
// expected output: Object { a: 1, b: 2}

console.log(newObj);
// expected output: Object { a: 1, b: 4, c: 5 } // the target property is overwrite by source
```

### Cloning an object 
``` javascript
const obj = { a: 1 };
const copy = Object.assign({}, obj);
console.log(copy); // { a: 1 }
```

Here the cloning has two different behaviors if the object has no inner object then the cloning work as deep clone and when the cloning object has any nested object the cloning work as shallow copy only for nested object, it will be more cleared with example:
``` javascript
let obj1 = { a: 0 , b: { c: 0}};
let obj2 = Object.assign({}, obj1);
console.log(JSON.stringify(obj2)); // { "a": 0, "b": { "c": 0}}

obj1.b.c = 3; // it reflect the changes in every shallow copy
console.log(JSON.stringify(obj1)); // { "a": 0, "b": { "c": 3}}
console.log(JSON.stringify(obj2)); // { "a": 0, "b": { "c": 3}}
```

In above example the `obj1` has the inner object like this `b: { c: 0}` so this object's reference will be shared with all new clones and change in one place will cause in all places.

##3. Object.keys(): <a name="keys"></a>
`Object.keys()` create and return an array containing the keys/names of an object.
``` javascript
let student = {
	name: "Abid",
	age: 23,
	status: "Student"
};
console.log(Object.keys(Student)) // ['name', 'age', 'status']
console.log(Object.keys(Student))
```


## 4. Object.values() <a name="values"></a>
Object.values() create an array containing the values of an object.
``` javascript
let student = {
	name: "Abid",
	age: 23,
	status: "Student"
};
console.log(Object.values(Student)) //  ['Abid', 23, 'Student']
```


## 5. Object.entries(): <a name="entries"></a>
Object.entries() returns an array of the key/values pairs of an object.
``` javascript
let student = {
	name: "Abid",
	age: 23,
	status: "Student"
};
console.log(Object.entries(student)) // [ ["name", "Abid"], ["age", 23], ["status", "Student"]]
```


## 6. Object.fromEntries() <a name="freomEntries"></a>
Object.fromEntries() does the exact opposite of Object.entries(). It takes an array of key values pairs and convert them into single object.
``` javascript 
let student = {
	name: "Abid",
	age: 23,
	status: "Student"
};
let studentArray = [["name", "Abid"], ["age", 23], ["status", "Student"]];
console.log(Object.fromEntries(studentArray)) // {name: 'Abid', age: 23, status: 'Student'}
```


## 7. Object.freez() and Object.seal() <a name="freez&seal"></a>
**Common Points:**
- Both prevents a JavaScript object from being altered.
- You can’t add new properties
- You can’t remove existing properties.

**Difference:**
`Object.seal()` allows the modification of existing properties.

![freez vs seal](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/jqop8gvvf02gnsrn8ihn.png)

_Note:_ The compiler does not throw any error if we violate any of the above mentioned rule.

**Code Level Example (freez and seal)**
``` javascript
let frozen = Object.freeze({ username: "Abid"})
let sealed = Object.seal({ username: "Abid"})

// Adding new Property 
frozen.name = "Ahmed"
sealed.name = "Ahmed"

// removing existing property
delete frozen.username;
delete sealed.username;

// updating the existing property
frozen.username = "Ahmed"
sealed.username = "Ahmed"

console.log(frozen) // { username: 'Abid' }
console.log(sealed) // { username: 'Ahmed' }
```

**Important Points: (freez and seal)** 

- Remember that both methods perform a shallow freeze/seal on the object.
- This means that nested objects and arrays are not frozen or sealed and can be changed.
- To prevent this, you need the concept of deep freezing of objects which I will be discussing in upcoming post


<a href="https://www.buymeacoffee.com/abidullah786"><img src="https://res.cloudinary.com/practicaldev/image/fetch/s--n7XsGLsY--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_800/https://cdn.buymeacoffee.com/buttons/v2/default-blue.png" alt="Buy-me-a-coffee" loading="lazy" width="545" height="153"></a>

<hr/>

Exploring new concepts in #JavaScript and sharing with others is my passion and it gives me pleasure to help and inspire people. If you have any suggestion or want to add something please comment.

If you liked my work connect with me on <a href="https://twitter.com/abidullah_786">Twitter</a>, <a href="https://www.linkedin.com/in/abidullah786/">Linkedin</a>and <a href="https://github.com/abidullah786">GitHub</a> to stay updated and join the discussion!