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.
How to Assign Default Values for Object Properties
To assign default values for all properties in an object that are undefined, follow these steps:
- Open the Terminal/SSH and type
nodeto start practicing coding. - Use
Object.assign()to create a new empty object and copy the original one to maintain key order. - Use
Array.prototype.reverse()and the spread operator (...) to combine the default values from left to right. - Finally, use
objagain 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.