Problem with return algorithm scripting

Hey guys,

I “solved” the first challenge but i can pass the test of freeCodeCamp.

Code

var myArray = [5, 6, 10];
var max = 0;
var min;
var result = 0;

function sumAll(arr) {
  // max of array
  for (let i = 0; i < arr.length; i++) {
    if (myArray[i] > max) {
      max = myArray[i];
    }
  }
  min = max;
  console.log(max);
  // min of array
  for (let i = 0; i < arr.length; i++) {
    if (myArray[i] < min) {
      min = myArray[i];
    }
  }
  console.log(min);
  //calc result
  for (let i = min; i <= max; i++) {
    result += i;
  }
  console.log(result);
}
sumAll([1, 4, 2]);

My problem is i have to return the “result” but if I use return my function get immediately stopped. I don´t know how to use the return statement at this point.

cheers
Flo

post your code with the return statement- where are you putting it?
you are right that a return statement stops the function, but if it is stopping the function at the wrong time then it is at the wrong place

Sorry I missed that…

var myArray = [1, 4, 2];
var max = 0;
var min;
var result = 0;

function sumAll(arr) {
  // max of array
  for (let i = 0; i < arr.length; i++) {
    if (myArray[i] > max) {
      max = myArray[i];
    }
  }
  min = max;
  console.log(max);
  // min of array
  for (let i = 0; i < arr.length; i++) {
    if (myArray[i] < min) {
      min = myArray[i];
    }
  }
  console.log(min);
  //calc result
  for (let i = min; i <= max; i++) {
    result += i;
  }
  return result;
}
sumAll([1, 4,]);

Your code contains global variables that are changed each time the function is run. This means that after each test completes, subsequent tests start with the previous value. To fix this, make sure your function doesn’t change any global variables, and declare/assign variables within the function if they need to be changed.

Example:

var myGlobal = [1];
function returnGlobal(arg) {
  myGlobal.push(arg);
  return myGlobal;
} // unreliable - array gets longer each time the function is run

function returnLocal(arg) {
  var myLocal = [1];
  myLocal.push(arg);
  return myLocal;
} // reliable - always returns an array of length 2

Additionally, I’m confused by your myArray global variable. Where does that come from?

1 Like

So, I finally got it thanks for the explanation :slight_smile:

I did a lot of testing and forgot to delete the array ^^ My bad.

here is the final code:

function sumAll(arr) {
  var max = 0;
  var min;
  // max of array
  for (let i = 0; i < arr.length; i++) {
    if (arr[i] > max) {
      max = arr[i];
    }
  }
  min = max;
  console.log(max);
  // min of array
  for (let i = 0; i < arr.length; i++) {
    if (arr[i] < min) {
      min = arr[i];
    }
  }
  console.log(min);
  //calc result
   var result = 0;
  for (let i = min; i <= max; i++) {
   
    result += i;
  }
  return result;
}
sumAll([1, 4,]);

Congratulations on figuring it out. Happy coding!