How to get values from inner function

Viewed 138

I need to get values(arr, sum) from inner function fn. i try to push it to results array in outer function or try to assign it like this a = fn();, no go. What i do wrong and how do i get this values in outer function?

    function func(limit) {
      let results = [];
      let arr = [];

      console.log(limit);
      function fn() {
        let arg = arguments;
        let sum = 0;
        for (let i = 0; i < arg.length; i++) {
          sum += arg[i];
          arr.push(arg[i]);
        };
        fn();
        console.log(arr, sum);
        results.push({args: arr, result: sum});
        return sum;
      };
      fn();
      console.log(results);
      return fn;
    };

  const mSum = func(2);
  console.log(mSum(3,4,5));

func returns 12, as intended, but i also need to further work with results array, so i try to use

results.push({args: arr, result: sum});

is you use console.log(arr, sum); you can see its there, but how do put it in aouter function func? in result it pushes keys, but values are empty array and 0.

5 Answers

You could return the object, instead of a single value.

function func(limit) {
  function fn() {
    let arg = arguments;
    let sum = 0;
    for (let i = 0; i < arg.length; i++) {
      sum += arg[i];
      arr.push(arg[i]);
    };
    return { args: arr, result: sum };
  }

  let results = [];
  let arr = [];
  return fn;
};

const mSum = func(2);
console.log(mSum(3, 4, 5));

You are returning a function. Not the result. So const mSum = func(2); returns your function. If you want the results of that function , you have to invoke it

const mSum = func(2); // function 
console.log(mSum()); //return value of the returned function

You can do something like

function fn() {
  ...
  return {args: arr, result: sum};
};

Then you will be able get both arr and sum from this function like

const { args, result } = fn();
    function func(limit) {
      let results = [];
      let arr = [];

      console.log(limit);
      function fn() {
        let arg = arguments;
        let sum = 0;
        for (let i = 0; i < arg.length; i++) {
          sum += arg[i];
          arr.push(arg[i]);
        };
        console.log(arr, sum); 
        results.push({args: arr, result: sum});
        return results;    // return 'results' rather than sum
      };
      console.log(results); // When you console.log(results), fn is not running yet, so you get a []
      return fn;   
    };

  const mSum = func(2);
  const mSum2 = mSum(3,4,5);  
  console.log(mSum2[0].args,mSum2[0].result);

At first you got some error in your code.

in function fn() you define let arg = arguments. But you never did define arguments, so the for loop won't iterate.

Also you are returning a function, not the result. You could get the result by the following code;

const mSum = func(2);
console.log(mSum());
Related