Assign Default Values for Object Properties

JavaScriptJavaScriptBeginner
Practice Now

This tutorial is from open-source community. Access the source code

Introduction

In this lab, we will explore a JavaScript function that assigns default values for object properties. This function helps streamline the process of ensuring that all properties in an object have a value, even if they were originally undefined. By using the Object.assign() method and spread syntax, we can easily create a new object with default values while maintaining the original key order.


Skills Graph

%%%%{init: {'theme':'neutral'}}%%%% flowchart RL javascript(("`JavaScript`")) -.-> javascript/BasicConceptsGroup(["`Basic Concepts`"]) javascript(("`JavaScript`")) -.-> javascript/AdvancedConceptsGroup(["`Advanced Concepts`"]) javascript/BasicConceptsGroup -.-> javascript/variables("`Variables`") javascript/BasicConceptsGroup -.-> javascript/data_types("`Data Types`") javascript/BasicConceptsGroup -.-> javascript/arith_ops("`Arithmetic Operators`") javascript/BasicConceptsGroup -.-> javascript/comp_ops("`Comparison Operators`") javascript/AdvancedConceptsGroup -.-> javascript/destr_assign("`Destructuring Assignment`") javascript/AdvancedConceptsGroup -.-> javascript/spread_rest("`Spread and Rest Operators`") subgraph Lab Skills javascript/variables -.-> lab-28267{{"`Assign Default Values for Object Properties`"}} javascript/data_types -.-> lab-28267{{"`Assign Default Values for Object Properties`"}} javascript/arith_ops -.-> lab-28267{{"`Assign Default Values for Object Properties`"}} javascript/comp_ops -.-> lab-28267{{"`Assign Default Values for Object Properties`"}} javascript/destr_assign -.-> lab-28267{{"`Assign Default Values for Object Properties`"}} javascript/spread_rest -.-> lab-28267{{"`Assign Default Values for Object Properties`"}} end

How to Assign Default Values for Object Properties

To assign default values for all properties in an object that are undefined, follow these steps:

  1. Open the Terminal/SSH and type node to start practicing coding.
  2. Use Object.assign() to create a new empty object and copy the original one to maintain key order.
  3. Use Array.prototype.reverse() and the spread operator (...) to combine the default values from left to right.
  4. Finally, use obj again to overwrite properties that originally had a value.

Here's an example code snippet:

const defaults = (obj, ...defs) =>
  Object.assign({}, obj, ...defs.reverse(), obj);

defaults({ a: 1 }, { b: 2 }, { b: 6 }, { a: 3 }); // { a: 1, b: 2 }

This code snippet will return an object that has default values for all properties that were undefined in the original object.

Summary

Congratulations! You have completed the Assign Default Values for Object Properties lab. You can practice more labs in LabEx to improve your skills.

Other JavaScript Tutorials you may like