Object nullish coalescing operator

Proposal: GitHub - bertyhell/proposal-object-nullish-coalescing-operator: A proposal to introduce new shorthand assignment for ECMAScript object literals where the value is falsey/undefined/null

This proposal shows a new syntax for assigning properties to an object literal but only if the object is not falsy/null or undefined.

Short example:

const myPersonObj = {
	firstName: person.name,
	work?: person.occupation,   // Only set work if person.occupation is truthy, by using the "?:" operator
	street??: person.address    // Only set street is person.address is not null and not undefined, by using the "??:" operator
};

I'm looking for feedback on:

  • Finding a champion. Or if i can be the champion myself, how to do that?
  • Should we add both operators? "?:" and "??:", or should we just add "?:" and have the behavior follow the modern nullish coalescing operator (only on null or undefined).
  • What impact does this have on the interpreter process? (V8). Is this an easy change, or would detecting these operators cause the interpretation of object literals to significantly slow down?
  • Feedback on shorthand notation. See the chapter "Other considerations"
2 Likes

You need only one of them, because person.occupation || null is nullish if and only if person.occupation is falsy:

const myPersonObj = {
	firstName: person.name,
	work??: person.occupation || null, 
	street??: person.address 
};

Good point.

So only keep the "??:" operator since it most closely matches the nullish coalescing operator "??".
That would be cleanest yes.

Hi @bertyhell , I find your idea worth considering.

Today to achieve the same I'm using longer construction. It's either with preliminary destructuring:

const {
  occupation: work,
  address: street,
  name: firstName
} = person;

const myPersonObj = {
  ...firstName && { firstName },
  ...occupation && { occupation },
  ...address && { address },
};

or without:

const myPersonObj = {
  ...person.name && { firstName: person.name },
  ...person.occupation && { occupation: person.occupation },
  ...person.address && { address: person.address },
};
1 Like