Hi all! I had an idea for a feature that I would be a really great addition to the language, and was curious on others' thoughts.
As declarative Javascript is used more and more, there is no easy way to conditionally add an element to an array in a declarative way.
I am proposing an "empty spread" operator, that allows one to return a "no elements" expression in a syntax similar to the current spread operator. Here's an example:
// current ways
const pets = [
"Dogs",
"Hamster",
"Penguin",
...(hasCats ? ["Cats"] : []),
];
let pets = ["horse];
if (horses) {
pets.push(horses);
}
// new way
const pets = [
"Dogs",
"Hamster",
"Penguin",
hasCats ? "Cats" : ...,
];
pets = ["horse", cow ?? ...];
See here for more examples. It is currently possible but really hard to read as a human.
I believe that an easy way to conditionally declaratively add something to an array or map would be great for reducing bugs and code complexity from two fronts. First, it would allow more code to be written declaratively and immutably. Second, it would make declarative code easier to read in situations like this.
This operator would have the same psudo-LHS characteristics as the normal spread operator - it cannot be assigned to a variable, nor returned by a function. I believe that JavaScript already has enough types to represent a value lacking some sort of trait (null, undefined), and making this its own type would add complexity to code. These operators should only be allowed to be defined within literal array and object field blocks.
A corollary is doing the same for objects. While in a lot of code patterns undefined in an object lookup is seen as there being no key, the in
keyword and hasOwnProperty
function actually return true if there is a key set to undefined in an object.
Syntax Possibilities I've thought of:
… - Most compact solution with spread operator
(…) - Wider empty expression with spread operator with parenthesis providing separation from potential camoflauged commas
[…], {…} - Case specific operators, with relations to expression, potentially confusing
() - Signifies an empty expression, also potentially confusing for use
I'm working on a babel polyfill proof-of-concept here right now, most things work, there are a few bugs I'm trying to squash with the ... operator in babel.