Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why ISN'T `foo: 'bar'` a syntax error in Javascript? [duplicate]

A coworker of mine wrote the ES6 line of code...

return map(orderedContentUuids, contentUuid => { uuid: contentUuid });

As you can probably guess he intended to return the object {uuid: contentUuid }, but since its an arrow function, the curly brace { actually starts a new block. (The correct code would be return map(orderedContentUuids, contentUuid => ({ uuid: contentUuid }));).

But, unexpectedly, this code transpiles and runs without an error. There's no error because uuid: contentUuid seems to evaluate to contentUuid.

You can see then that if you put into your JavaScript console foo: 'bar' it evaluates to "bar".

Huh? What's going on. Since when is that valid JS?

like image 704
Chris W. Avatar asked Dec 21 '17 00:12

Chris W.


1 Answers

Ooops. I just figured it out.

foo: 'bar' is evaluated as a "label", which I did not realize was a JavaScript feature.

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/label

like image 134
Chris W. Avatar answered Nov 15 '22 00:11

Chris W.