Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is this valid syntax?

While refactoring some code I accidentally discovered that this is valid syntax (or at least, doesn't cause a parser error in Firefox):

const {} = somefunc();

somefunc returns an object and the curly's are supposed to contain variable names for destructuring, at the time I hadn't decided what those names would be so I temporarily left them empty.

The editor didn't highlight a syntax error, so out of curiosity I tested it, and was surprised that Firefox actually had no issue with this syntax.

Why is this syntax valid? Does it actually do something weird?

like image 769
DJL Avatar asked May 06 '20 14:05

DJL


3 Answers

Yes, empty destructuring like that is perfectly fine, it's just useless. This is covered in Runtime Semantics: DestructuringAssignmentEvaluation

With parameter value.

ObjectAssignmentPattern: {}

  1. Perform ? RequireObjectCoercible(value).

  2. Return NormalCompletion(empty).

All it does (in RequireObjectCoercible) is require that the right side is not null nor undefined.

like image 142
CertainPerformance Avatar answered Nov 17 '22 15:11

CertainPerformance


When destructuring an object you chose which properties you need:

const {a, c} = {'c': 1, 'b': 2, 'a': 3};

Thus having no parameters is acceptable, but useless nonetheless:

const {} = {};
like image 33
emix Avatar answered Nov 17 '22 15:11

emix


It's just the limiting case of object destructuring.

While it may seem pointless to allow it, allowing edge cases like this is useful for automatically generated code, so the generator doesn't have to check that there are zero items and skip generating the code.

like image 4
Barmar Avatar answered Nov 17 '22 17:11

Barmar