Optional properties in object literals

This is an idea for a JavaScript proposal. It would be nice to have a quick way to conditionally add properties to an object literal. More specifically when the value is undefined it is often preferred to not have the property at all in the object. For example:


const value = something();

const obj = { a: 1 };

if (value !== undefined) {

obj.b = value;

}

or


const value = something();

const obj = { a: 1, ...(value ? { b: value } : {}) };

This is very verbose. My proposal is to add a "?" operator to object literals. This operator would only add the property if the value is not undefined. For example:


const value = something();

const obj = { a: 1, b?: value };

If value is undefined then obj would be { a: 1 }. If value is not undefined then obj would be { a: 1, b: value }.

Other examples:


const headers = { "Content-Length"?: length };

const obj = { [key]?: value };

Why only undefined? Because it matches the behavior of JSON serialization. If you serialize an object with JSON.stringify and the value is undefined then the property is not included in the JSON string.

Similar discussion in this topic: Conditionally add elements to declaratively defined arrays

Practically speaking, engines are better able to optimize code when objects have the same shape, i.e. all the same keys in the same order. So programs will generally perform better if you include the property and leave it as undefined, rather than omitting the property. As such I don't think we should be adding syntax to encourage this pattern.