1

I wrote the following code that outputs the sum of squared iterating numbers:

(function () {
    var i = 4, sum = 0; 
    while(i--) sum+=i*i;
})();
console.log(sum);

The problem is I get the following error in console: sum is undefined unless I take the sum out and declare it as global scope: //this works but this is not what I want.

sum = 0;    
(function ( ) {
    var i=4 
    while(i--) sum+=i*i;
})();
console.log(sum);

Could some one help me understand? Thanks

1
  • It's an issue of scope. You can't use the sum variable outside of the scope in which it was declared. If you're going to log sum in the global scope, then you must declare it globally. I see nothing wrong with using the code as it exists above. Commented Sep 24, 2011 at 16:32

4 Answers 4

5
var sum = (function ( ) {
  var i=4, sum = 0; 
  while(i--) sum+=i*i;
  return sum;
})();
console.log(sum);

You created a local variable called sum and want to use it outside it's scope. You don't want to declare it in a higher scope so you have to export it.

The only way to export local (primitive) variables is the return statement.

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

Comments

3

A self-invoking function has its own scope (i.e. place to live for variables), so sum ceases to exist after the function and all dependent closures finished executing and it is not accessible from outside. In fact, having a separate scope that won't spoil the global or any other scope is the main reason why People use self executing functions.

Comments

1

Because you are accessing sum outside your function scope at the line: console.log(sum), where sum is not visible.

If you do not want to put sum in global scope, then you got to take the statement console.log(sum) within the function scope.

Comments

0

you are defining sum inside the function which is local variable. and printing the sum outside the function which is out of scope.

Comments

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.