Binge On Code

Jun 14, 2023

9 readers

How To Provide Optional Property In JavaScript Object.

Let’s see how we can have JavaScript object optional property in a few lines of code. This can be really helpful, especially when you want to be concise as possible.

For this simple guide, we will solve for JavaScript object optional property, by using a hypothetical Software Engineer model.

 

interface Engineer {

 name: string;

 /**

  * other properties go here

  */

 isFullStack?: boolean;

}

 

The Engineer can be a fullstack, and if they are not fullstack, then we don’t need to set it as false.

 

const isEngineerFullStack = () => {

 /**

  * Do some calculation here, but for now, we will return false

  * just for the purpose of this demonstration.

  */

 return false;

};

 

We have a simple method to check the status of whether Engineer is fullstack.

 

const engineer: Engineer = {

 name: "Binge On Code",

 ...(isEngineerFullStack() ? { isFullStack: true } : {}),

};


console.log("engineer", engineer);

 

Now the most important part is:

 

...(isEngineerFullStack() ? { isFullStack: true } : {})

 

and what we are doing here is optionally spreading the Engineer object, and providing the isFullStack property,  and on false, we are spreading an empty object.

 

console.log("engineer", engineer);


/**

* engineer { name: 'Binge On Code' }

*/

 

And that is it!

Application

With optional property JavaScript object, you can be able to send only the needed payload to the backend, and use defaults on your backend for the missing values!

Happy Coding!

 

Related Articles

Code Splitting And Lazy Loading

Code Splitting and lazy loading are basically augmentations of one another. Lazy loading builds on top of the power of code splitting.

Jun 7, 2023

Views 498

Destructure JavaScript Object With Defaults

You can really simplify your access to your JavaScript objects by using this simple method to destructure JavaScript object with defaults.

Jun 20, 2023

Views 27

Get Index Of Item In JavaScript For Of Loop

In a few lines of code, you will see how easy it is to get an item’s index in JavaScript For Of Loop. Let’s do this!

Jun 16, 2023

Views 34

Angular JavaScript React CSS Django Python React Native Next JS State Management Django Rest Framework Unity