5

could anybody please explain the difference between the following snippets..

var a = function(){
       return function(){
                  //some code 
                        }
                  }();

and

 var a = function(){
                  //some code
                   }

I understand we use return function to access variables defined in the parent function and this is a self-executing function but in the first case the first function does nothing but return the other function. I have seen this type of functions a couple of times and am not able to figure out what it is for. Also please explain the above function

var session = (function(){return ${session}})();

and

var session = ${session};
2
  • 4
    Since there are no local variables declared in the functions, there is no practical difference. Commented Jan 9, 2014 at 7:10
  • @Quentin :That is what i was wondering about.. thanks.. Commented Jan 9, 2014 at 7:12

2 Answers 2

1

I am 95% confident that the official answer here should be, at least in the two examples cases from the OP, that the use of an IIFE is superfluous. In the two examples, the unwrapped versions are preferable and clearer.

One other possibility that hasn't been mentioned is that the code samples may be coming from one of the many languages that compiles into JavaScript, such as a coffeescript. It may be that wrapping with IIFE is a good general strategy for the compiler, but that it sometimes results in superfluous code such as the OP's examples.

Sign up to request clarification or add additional context in comments.

Comments

0

You need to read two things Closures and Function and function scope.

1 Comment

@Jonah gave another thought on it and updated the answer also w.r.t the code in the question you seem to be right. I had answered it in a generic way. Thanks.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.