String-Key-Only Object Declaration - Just like Array, but with direct access

Context

Consider the following code

const ext = 'webp';
const o = { 'html': 1, 'css': 1, 'mjs': 1, 'js': 1, 'json': 1 };
console.log(o[ext] ? 'Found' : 'Not found'); 

To check if an element exists in a collection, its declaration is unecessary verbose.
Lots of useless 1's here.

Proposal

I suggest to be able to replace

const o = { 'html': 1, 'css': 1, 'mjs': 1, 'js': 1, 'json': 1 };

by

const o = { 'html', 'css', 'mjs', 'js', 'json' };

Just like an array, but with direct access.

Q / A

Q : It has to be a valid Object. What about the value ?
A : The implicit behavior is : Value equals Key

It means

const o = { 'html', 'css', 'mjs', 'js', 'json' };

is implicitely interpreted as

const o = { 'html':'html', 'css':'css', 'mjs':'mjs', 'js':'js', 'json':'json' };

--

Q : What about spread ?
A : You can do that.

It means

const o = { 'html', 'css', ...{ 'mjs', 'js' }, ...{ 'json' } };

is implicitely interpreted as

const o = { 'html':'html', 'css':'css', ...{ 'mjs':'mjs', 'js':'js' }, ...{ 'json':'json' } };

--

Q : What about self-assignment ?
A : Self-assignment is impossible, it would conflict with accessing to the property.

Ex:

const o = Object();
o.html;
o['css'];

It cannot be a write operation.
It is a read-only operation.
Self-assignment is impossible.

--

See also : when object declaration passed with single string, consider the same string as key == value like variable shorthand

Surma says to use :

const ext = 'webp';
const o = new Set([ 'html', 'css', 'mjs', 'js', 'json' ]);
console.log(o.has(ext) ? 'Found' : 'Not found'); 
2 Likes

Is there a difference to the other thread?

1 Like