Reputation: 44051
In the code below I firstly try to print the 'normal' way. Secondly I try to anonymize my function and assign it to a variable which I then print. In Chrome this now proceeds to print the source code. What am I doing wrong?
function sumSq() {
var sum = 0;
for (i=0;i<=10;i++) {
sum+=i*i;
}
return sum;
}
console.log(sumSq());
var mySum = function() {
var sum = 0;
for (i=0;i<=10;i++) {
sum+=i*i;
}
return sum;
}
console.log(mySum);
Upvotes: 0
Views: 107
Reputation: 160853
var mySum = function() {
var sum = 0;
for (i=0;i<=10;i++) {
sum+=i*i;
}
return sum;
}
is just the same with:
function mySum() {
var sum = 0;
for (i=0;i<=10;i++) {
sum+=i*i;
}
return sum;
}
And call it console.log(mySum());
Upvotes: 1
Reputation: 62185
Call mySum
using ()
:
console.log(mySum());
Functions are objects, so when you call
console.log(mySum);
JS calls toString on the mySum object (which mySum inherits from the Object prototype). That's why the source gets printed.
Upvotes: 1
Reputation: 10685
Function should be called as mySum()
Apart from this, both ways do the same.
Upvotes: 1