1

In Java/C/C++ (and, with the exception of Python, every other language I can think of) whitespace is ignored.

I've just spent several hours trying to work out why I was getting an error on a return statement. The answer was whitespace.

So here are the two code snippets that I thought were functionally equivalent.

return { a:b, c:d};

return
{
a:b,
c:d
};

But I now understand that the first one works but the second one throws an error on the c:d line.

Can someone explain why these are not syntactically equivalent?

Quentin
  • 800,325
  • 104
  • 1,079
  • 1,205

1 Answers1

5

The problem here is that JavaScript has a "feature" called automatic semi-colon insertion.

So, your second snippet was actually being executed like this (note the semi-colon after the return):

return;
{
a:b,
c:d
};

Basically, you were returning undefined, rather than the object literal.

JavaScript has so called "bad parts" and you ran in to one of them. I would highly recommend reading this book regarding the subject.

See this article for more information about automatic semi-colon insertion.

If you still wanted to format your code similarly to what you originally had, this might be the closest that wouldn't bite you:

return {
a:b,
c:d
};
Jonathan.Brink
  • 19,445
  • 13
  • 59
  • 98
  • As a side note, you can safely start it with `return (` followed by your object with line breaks (without the final semicolon), followed by `);` – Arnauld Jul 01 '16 at 13:12
  • 1
    My god I already hate JS. The more I use it the worse it looks. But thanks for the prompt response. Fortunately I have to do less and less Javascript. We moved dev to Vaadin which virtually eliminates the need for HTML, Javascript and not much css required. Only problem with Vaadin is that we now don't have enough testers. Developer have almost doubled output. But javascript is cool, so what do I know :D – Brett Sutton Jul 01 '16 at 13:36