1

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);

3 Answers 3

4

you are loggin the function itself not the returned value.

var a=calculateSum(firstValue, firstArray);
console.log(a);

it outputs 13;

Sign up to request clarification or add additional context in comments.

2 Comments

Got it, thanks. What I don't seem to understand is why-in the reasoning of informatics, console.log(firstValue) still gives zero. There's supposed to be a reserved memory spot within a computer that modifies the original 0 value everytime it goes through the loop.
because javascript passes arguments as value not reference (for primitive types such as strings and numbers).so when you pass varibale to function the variable remains as it is.
3

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);

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.