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
Because you are accessing
sumoutside your function scope at the line:console.log(sum), where sum is not visible.If you do not want to put
sumin global scope, then you got to take the statementconsole.log(sum)within the function scope.