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
sumvariable outside of the scope in which it was declared. If you're going to logsumin the global scope, then you must declare it globally. I see nothing wrong with using the code as it exists above.