3
function a(){
 return{
    bb:"a"
 }
}

and 

function a(){
 return
 {
    bb:"a"
 }
}

Is there any difference between the two code, if yes please explain.

Rishi0405
  • 354
  • 1
  • 11

2 Answers2

10

The difference is huge. The first returns an object. The second - undefined due to Automatic Semicolon Insertion. return will become return;

function a(){
 return{
    bb:"a"
 }
}


function a1(){
 return
 {
    bb:"a"
 }
}

console.log(a(), a1())
Yury Tarabanko
  • 44,270
  • 9
  • 84
  • 98
  • just a footnote: ASI stands for "Automatic Semicolon Insertion" -> https://stackoverflow.com/questions/2846283/what-are-the-rules-for-javascripts-automatic-semicolon-insertion-asi – Alex Jul 14 '17 at 08:15
3

For some reason, the Javascript bods decided that a single return on a line will be subject to a sort of "auto-correct" mechanism called Automatic Semicolon Insertion.

So your second snippet becomes

function a1(){
 return;
 {
    bb:"a"
 }
}

which is no longer syntactically valid!

Reference: What are the rules for JavaScript's automatic semicolon insertion (ASI)?

(I'm currently learning Javascript myself and have already fallen for this.)

Bathsheba
  • 231,907
  • 34
  • 361
  • 483
  • 1
    Ok . I can die in shame now :D Have an upvote for the new thing today. – Suresh Atta Jul 14 '17 at 08:21
  • @SureshAtta: Could you have a robust conversation with the dudes who decided this was a good idea first? You can be the fall guy! Luckily for me, I use K&R style for C and C++, so this won't jab me too often. – Bathsheba Jul 14 '17 at 08:21