Javascript Objects: Best Practices
Tags: javascript, webdev, beginners, frontend
Published: 2023-06-17 08:24:11

While working on Javascript we have to deal with objects as its a building block of the Javascript. Knowing how to use the objects effectively makes your code more readable, efficient, and bug free. In this blog we are going to see a few good practices while working with objects in Javascript.So lets get started !

### **Tip 1: Use the literal syntax for object creation**
This seems to be a small change while initialising the objects variable , but after knowing this information you will better understand why this is important.

```javascript
// not recommended
const item = new Object();

// good practice
const item = {};
```

- The literal syntax provides a concise and intuitive way to define objects. It is easier to read and understand compared to the Object constructor, which requires invoking a function with the new keyword.

- Creating objects with the literal syntax is faster compared to using the Object constructor. The literal syntax directly creates the object without invoking any additional functions or constructors.

- Object constructor is actually a property of the global object, so it can be overwritten.This can be dangerous!
consider the below code-
```javascript
Object = 10;
var obj = new Object();
```
This will throw an error `TypeError: Object is not a constructor` as the Object property is assigned to a number 10;

### **Tip 2: Use computed property names**

```javascript
function getKey(k) {
  return `${k}_key`; //generates key name dynamically
}

// not recommended
const obj = {
  id: 1,
  name: 'Foo',
};
obj[getKey('enabled')] = true;

// good practice!
const obj = {
  id: 1,
  name: 'Foo',
  [getKey('enabled')]: true, // computed property syntax
};
```
This will allow to define all the properties at once while creating the object.

### **Tip 3: Use object method and property shorthand**

- use object method shorthand
```javascript
// looks ugly
const obj = {
  value: 1,

  addValue: function (value) {
    return this.value + value;
  },
};

// looks clean!
const obj = {
  value: 1,

  addValue(value) {
    return this.value + value;
  },
};
```
- use property value shorthand

```javascript
const property = 'property';

// looks ugly
const obj = {
  property: property,
};

// good practice
const obj = {
  property,
};
```
Group all shorthand properties at the beginning of your object declaration.In this way it's easier to see which properties are using the shorthand.

### **Tip 4: Provide quotes for properties with invalid identifiers**

There is no need to quote all the properties defined inside the object. This hampers the readability and object looks bulky. If you are using any invalid identifiers such as identifiers with kebab cases, then you can quote that particular property.

```javascript
// bulky
const obj = {
  'prop1': 1,
  'prop2': 2,
  'prop-3': 3,
};

// good practice!
const obj = {
  prop1: 1,
  prop2: 2,
  'prop-3': 3,
};
```

### **Tip 5: shallow / deep copy object to avoid object mutability**

There are few tricks and methods which allows the object to be copied to another object variable to avoid mutating the original object. Based on the requirement we can create a shallow copy or deep copy of the original object or else completely store the reference of the original object into another object variable.

- avoid using `Object.assign()` in this way:
```javascript
const originalObj = { a: 1, b: 2 };
const copiedObj = Object.assign(originalObj, { c: 3 }); // this mutates `originalObj`
delete copiedObj.a; // this will be deleted from the originalObj as well!!!!
```
- shallow copy using `Object.assign`:
```javascript
const originalObj = { a: 1, b: 2 };
const copiedObj = Object.assign({}, originalObj, { c: 3 }); // copy => { a: 1, b: 2, c: 3 }
delete copiedObj.a
console.log(originalObj) // {a: 1, b: 2}
console.log(copiedObj) // {b: 2, c: 3}, 'a' is deleted from copiedObj
```

- shallow copy using spread object syntax:
```javascript
const originalObj = { a: 1, b: 2 };
const copiedObj = {...originalObj, c: 3} // copy => { a: 1, b: 2, c: 3 }
delete copiedObj.a
console.log(originalObj) // {a: 1, b: 2}
console.log(copiedObj) // {b: 2, c: 3}, 'a' is deleted from copiedObj
```

- deep copy using `JSON.parse` and `JSON.stringify`
```javascript
const originalObj = { a: 1, b: {
  b1: 1,
  b2: 2
} };
const copiedObj = JSON.parse(JSON.stringify(originalObj)) // copy => { a: 1, b: {b1: 1, b2: 2} }
delete copiedObj.b.b1
console.log(originalObj) // {a: 1, b: {b1: 1, b2: 2}}
console.log(copiedObj) // {a: 1, b: { b2: 2}}
```