6 Ways To Set Default Values for Objects in JavaScript

In JavaScript, working with objects is a fundamental aspect of programming.

There are times when you need to ensure that an object property has a default value if it’s not explicitly provided.

In this article, we’ll explore 6 ways and techniques, and code examples to set default values for object properties, ensuring your code remains robust and error-resistant.

Setting default values for object properties ensures that your code doesn’t break or produce unexpected results when certain values are missing.

This is particularly important when dealing with user inputs, API responses, and configurations

Method #1 Using the Logical OR Operator

One straightforward way to set default values is by using the logical OR (||) operator.

If the property is falsy (null, undefined, empty string), the default value is assigned.

const user = {
  username: null,
  age: undefined,
};

console.log(user.username || "Guest"); // "Guest"
console.log(user.age || 18); // 18

Method #2 Using Object Destructuring

Object destructuring provides a concise way to set default values during assignment.

const user = {
  username: null,
  age: undefined,
};

const { username = "Guest", age = 18 } = user;

console.log(username); // "Guest"
console.log(age); // 18

Method #3 Using the Object.assign() Method

The Object.assign() method can be used to merge an object with default properties.

const defaultUser = {
  username: "Guest",
  age: 18,
};

const user = {
  age: 25,
};

const mergedUser = Object.assign({}, defaultUser, user);

console.log(mergedUser); // { username: "Guest", age: 25 }

Method #4 Using Default Parameter Values

When using functions to create objects, you can set default parameter values.

function createUser({ username = "Guest", age = 18 }) {
  return { username, age };
}

console.log(createUser({ username: "John" })); // { username: "John", age: 18 }

Method #5 Handling Nested Objects

Setting default values for nested objects requires a slightly different approach.

const user = {
  profile: {
    name: null,
    location: "Unknown",
  },
};

const { profile: { name = "Anonymous", location = "Unknown" } } = user;

console.log(name); // "Anonymous"
console.log(location); // "Unknown"

Method #6 Considerations for Complex Default Values

When dealing with complex default values, like arrays or objects, ensure you’re not unintentionally sharing references between instances.

const defaultUser = {
  hobbies: [],
};

const user1 = Object.assign({}, defaultUser);
user1.hobbies.push("Reading");

const user2 = Object.assign({}, defaultUser);
user2.hobbies.push("Gardening");

console.log(user1.hobbies); // ["Reading", "Gardening"]
console.log(user2.hobbies); // ["Reading", "Gardening"]

Setting default values for object properties is an essential practice to ensure the stability and reliability of your JavaScript code.

See also  How to create a server in node.js in 4 steps

In this article, we explored various techniques for setting default values, including the logical OR operator, object destructuring, Object.assign(), default parameter values, and handling nested objects.

By applying these techniques appropriately, you can enhance the robustness of your applications, handle user inputs more gracefully, and ensure that your code behaves as expected even when certain values are missing.

Remember to choose the technique that best fits your specific use case, and make your code more resilient to unexpected scenarios.