Reputation: 353
I have successfully tried to create a function where the numerical value of all elements in an array are being added to a total number, but there seems to be a problem when it comes to assigning different variants for array's length and the array itself respectively.
So here's what ostensibly doesn't work for now
var firstValue = 0;
var secondValue = 0;
var firstArray = [8, 5];
var secondArray = [10, 10];
function calculateSum(x,y) {
for ( var i = 0; i < y.length; i++) {
x += y[i];
}
return x
}
calculateSum(firstValue, firstArray);
console.log(calculateSum);
Upvotes: 1
Views: 220
Reputation: 4292
you can use something like this and then add the result to where you need it. In this example you get sum of all values in yourArray and the firstValue.
var sum = yourArray.reduce(function(pe,ce){
return pe + ce;
}, firstValue);
link to some docs
Upvotes: 0
Reputation:
In the last line you have console.log(calculateSum)
, however this is the function and not the result of the function.
You need to store the result of calculateSum
and then log that.
var firstValue = 0;
var secondValue = 0;
var firstArray = [8, 5];
var secondArray = [10, 10];
function calculateSum(x,y) {
for ( var i = 0; i < y.length; i++) {
x += y[i];
}
return x
}
var result = calculateSum(firstValue, firstArray);
alert(result);
Upvotes: 3
Reputation: 3350
you are loggin the function itself not the returned value.
var a=calculateSum(firstValue, firstArray);
console.log(a);
it outputs 13;
Upvotes: 4