DEV Community

Code Craft-Fun with Javascript
Code Craft-Fun with Javascript

Posted on • Updated on

Javascript Objects: Best Practices

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.

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

// good practice
const item = {};
Enter fullscreen mode Exit fullscreen mode
  • 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-

Object = 10;
var obj = new Object();
Enter fullscreen mode Exit fullscreen mode

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

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
};
Enter fullscreen mode Exit fullscreen mode

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
// 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;
  },
};
Enter fullscreen mode Exit fullscreen mode
  • use property value shorthand
const property = 'property';

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

// good practice
const obj = {
  property,
};
Enter fullscreen mode Exit fullscreen mode

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.

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

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

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:
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!!!!
Enter fullscreen mode Exit fullscreen mode
  • shallow copy using Object.assign:
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
Enter fullscreen mode Exit fullscreen mode
  • shallow copy using spread object syntax:
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
Enter fullscreen mode Exit fullscreen mode
  • deep copy using JSON.parse and JSON.stringify
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}}
Enter fullscreen mode Exit fullscreen mode

Top comments (3)

Collapse
 
jonrandy profile image
Info Comment hidden by post author - thread only accessible via permalink
Jon Randy ๐ŸŽ–๏ธ • Edited

Prototype Chain Preservation: When using the Object constructor, the newly created object doesn't inherit from the global Object prototype. In contrast, when using the literal syntax, the object is created with the correct prototype chain intact.

This is entirely wrong.

Immutability: When using the literal syntax, it's easier to create immutable objects by using techniques such as Object.freeze() or ES6's object spread syntax ({...}), which can make the object properties read-only. This immutability helps prevent unintended modifications to the object.

Really, how? I don't see that it would be any easier or more difficult.

Syntax Errors Avoidance: The literal syntax allows for more flexibility when defining objects, such as using computed property names ({[key]: value}), shorthand property syntax ({key}), or object methods ({method() {}}). These features are not available when using the Object constructor.

This makes no sense whatsoever, please explain what you mean. I understand the flexibility point, but what does that have to do with syntax error avoidance?

Collapse
 
codecraftjs profile image
Code Craft-Fun with Javascript

Follow codecraftjs for more contents on Javascript
Follow Instagram page - @codecraftjs
- Javascript Core Concepts
- Javascript Tips & Tricks
- Javascript Frameworks (Angular, React)
- Paid Mentorship and Guidance

Collapse
 
ra1nbow1 profile image
Matvey Romanov • Edited

Thank you for the nice article

Some comments have been hidden by the post's author - find out more