0

I just run up into some code and then I did a test and found something I don't understand.

hey(
  () => {},
  () => {
    foo: "bar";
  }
);

Why the following syntax is a valid syntax? In the first argument, I can understand, because is an empty function scope, but in the second argument, how it doesn't give me an error?

If it's returning a object, it should be ({...}) and don't accept ; at the end, so this means that the second argument isn't an object.

If it isn't an object, what is it? Why it isn't a syntax error?

What black javascript magic is happening here?

Here is an example on codesanbox and it doens't give me any syntax error.

Edit

I just found some other weird thing.

hey(
  () => {},
  () => {
    "bar"; // without foo:
  }
);

How this doesn't give any error?

Vencovsky
  • 28,550
  • 17
  • 109
  • 176
  • 1
    after your edit: why would that give an error? You're allowed to have a string that doesn't do anything. It's meaningless, but no reason to error – TKoL Dec 18 '19 at 14:00

2 Answers2

5

If you skip the (), it's interpreted as a labeled statement

() => {
  foo: "bar";
}

If add another property, you can see the error clearly

() => {
  foo: "bar",
  baz: ''
}
adiga
  • 34,372
  • 9
  • 61
  • 83
-2

The second argument ISN'T an object. It's a function. The second argument is basically equivalent to saying

function() {
   foo: "bar";
}

Which in fact doesn't error, despite looking like it should

If you want an arrow function to return an object immediately, the syntax is

() => ({foo:'bar'})
TKoL
  • 13,158
  • 3
  • 39
  • 73