Difference between returning followed by curly braces and returning followed by curly braces on the next line

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

and 

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

      

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

+3


source to share


2 answers


The difference is huge. The first one returns an object. The second is undefined due to Automatic semicolon . return

will becomereturn;



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


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

console.log(a(), a1())
      

Run codeHide result


+11


source


For some reason, the Javascript boxes decided that one return

per line would be subject to some "automatic correct" mechanism called Automatic Semicolon Insertion.

So your second snippet becomes

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

      



which is no longer syntactically valid!

Ref: What are the rules for automatic semicolon insertion (ASI) for JavaScript?

(I am currently learning Javascript myself and have already dropped for this.)

+3


source







All Articles