How to access the arguments of parent function in nested function in javascript?

I am trying to find the maximum of two numbers using the following code using a nested function in javascript, however, I am encountering the following error in console "Uncaught ReferenceError: maximum is not defined", seems that the nested function val2 is not able to access the argument of function val. Any idea on how can we fix this?

function val(maximum)
{
    var val2=new Function('input','if(input>maximum){return("Number is greater");}else{return("Number is less")}');
    return val2;
}

var call=val(5);
console.log(call(2));

2 answers

  • answered 2021-05-13 18:58 user2599052

    maximum = 5;
    function val()
    {
        var val2=new Function('input','if(input>maximum){return("Number is greater");}else{return("Number is less")}');
        return val2;
    }
    
    var call=val();
    console.log(call(2));
    

    The above will work. In case you define functions using new Function, it doesn't close on the function from where it is created but closes on the global env. That why i have moved maximum outside and it works. You can read about closures for more on this.

  • answered 2021-05-13 19:02 Felix Kling

    seems that the nested function val2 is not able to access the argument of function val

    While you are creating the function inside another one, new Function behaves as if the function was created in global scope, i.e. it doesn't have access to the function environment it was created in. See MDN for more details.

    There is no reason to use new Function, you can just create the function directly and you will be able to access the outer function's arguments, because every function in JavaScript is a closure:

    function val(maximum) {
      return function(input) {
        if (input>maximum){
          return("Number is greater");
        } else {
          return("Number is less");
        }
      };
    }
    
    var call=val(5);
    console.log(call(2));

    I hope it goes without saying that this is better than writing code inside a string literal. There is almost never a reason to use new Function to create a function.