Reputation: 17
I wrote a simple program for learning purposes recently that (for now) basically just adds all the numbers together. But, for some reason, when I try to call it ( the programm is a function ), it puts out an "maximum call stack size exceeded" error. Is there any way to fix it? The answer may be very obvious, but I'm a very beginner at this stuff. Here's the code:
var add = function(num1, num2, num3, num4, num5) {
for(i = 0; i < add.length; i++) {
if(i === 0) {
var first = add(i);
} else if(i === 1) {
var second = add(i);
} else if(i === 2) {
var third = add(i);
} else if(i === 3) {
var fourth = add(i);
} else if(i === 4) {
var fifth = add(i);
console.log(first + second + third + fourth + fifth);
};
};
};
add(1, 2, 3, 4, 5);
Upvotes: 1
Views: 58
Reputation: 353
I believe you are learning about arguments.
Since doing a add.length
does not make any sense at all.
var add = function(num1, num2, num3, num4, num5) {
for (i = 0; i < arguments.length; i++) {
if (i === 0) {
var first = arguments[i];
} else if (i === 1) {
var second = arguments[i];
} else if (i === 2) {
var third = arguments[i];
} else if (i === 3) {
var fourth = arguments[i];
} else if (i === 4) {
var fifth = arguments[i];
}
}
console.log(first + second + third + fourth + fifth);
};
add(1, 2, 3, 4, 5);
You can write it like this
var add = function() {
var sum = 0;
for (var i = 0; i < arguments.length; i++) {
sum += arguments[i];
}
return sum;
};
console.log(add(1, 2, 3, 4, 5));
console.log(add(1, 2, 3, 4));
Functions are supposed to take arguments, process and then return the result.
Upvotes: 1