21

Consider these two functions.

function func1() {
   return
   {
      foo: 'bar'
   }
}

function func2() {
   return {
      foo: 'bar'
   }
}

alert(typeof func2()) //return object

alert(typeof func1()) //return undefined

Why does the position of the braces matter when in many other languages it does not? Is it a language feature or a bug?

Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335
Md Nazmoon Noor
  • 3,187
  • 1
  • 24
  • 30

1 Answers1

44

Because of automatic semicolon insertion. The first code is the same as

function func1() {
   return;
   {
      foo: 'bar'
   }
}

If you wonder why this code doesn't produce a syntax error, foo: is a label.

Regarding

Is it a language feature or a bug?

It's a feature. But a very dangerous one. The best way to keep it being a feature for you is to stick to consistent formatting style (I'd suggest to use the Google style guide until you're experienced enough to make your own).

Denys Séguret
  • 372,613
  • 87
  • 782
  • 758
  • This would be improved by a link to [12.9 The return Statement](http://www.ecma-international.org/ecma-262/5.1/#sec-12.9) that [Ejay pointed out](http://stackoverflow.com/questions/24120708/why-does-the-position-of-braces-in-javascript-matter#comment37213016_24120708). – Joshua Taylor Jun 09 '14 at 14:46