1
var calculator = function ()
{
   function abc() { return (2+3); }

   return {
        addFun: abc
   }
}();


var calcu = function () {
    function abc() { return (3+4); }

    return 
    {
        addFun: abc
    }
}();


$(document).ready(function () {
    alert(calculator.addFun());
    **alert(calcu.addFun());**
});

What is difference between calculator and calcu function? calcu function gives error when it execute.

Difference is only that curly bracket is next line in "calcu". It is work fine if I remove next and put curly bracket with "return" keyword.

Please explain why so?

Zong
  • 6,160
  • 5
  • 32
  • 46

5 Answers5

5

It's being parsed as this:

return; // returns undefined
// a block:
{
    addFun: abc // syntax error!
};

because of automatic semicolon insertion.

Change it to:

return {
     addFun: abc
};
tckmn
  • 57,719
  • 27
  • 114
  • 156
5

It's called automatic semicolon insertion:

When a continue, break, return, or throw token is encountered and a LineTerminator is encountered before the next token, a semicolon is automatically inserted after the continue, break, return, or throw token.

Since there's a newline right after your return statement, a semicolon is inserted automatically, turning your code into:

return;
{
    addFun: abc
}
Blender
  • 289,723
  • 53
  • 439
  • 496
2

Return is a tricky keyword in JavaScript. In the first example, you are returning an anonymous object to the calculator function, and in the second example you are returning no values. JavaScript will interpret the second function like this:

var calcu = function() { 
    function abc() ...

    return; // return undefined
    {
          addFun: abc
    }

Notice the semi colon is interpreted after the return keyword and thus the calcu function will return nothing.

Alec Moore
  • 1,155
  • 2
  • 10
  • 20
  • Yep, this is the case where parens around what you're returning removes all chance of the interpreter guessing your intentions wrong. I'm often criticized for using parens around my return values, but this is exactly the case where it's needed. – jfriend00 Jan 05 '14 at 17:54
1
return 
{
    addFun: abc
}

This is wrong because JavaScript would execute return and will get out. This should be

return {
    addFun: abc
}
Travesty3
  • 14,351
  • 6
  • 61
  • 98
Alex Shilman
  • 1,547
  • 1
  • 11
  • 15
1

Have a look at linting tools such as jshint to avoid this and many other errors, here is it's output:

enter image description here

What happens is that this section:

return 
{
    addFun: abc
}

is being interpreted as two statements, a return void (the function returns void immediatelly) plus an object expression containing addFun that is not assigned to anything.

Angular University
  • 42,341
  • 15
  • 74
  • 81