Tom Abarba
Tom Abarba

Reputation: 43

understanding the anonymous function scope and return value

I have a function the receives two ints, I want another variable to be initialized with the larger one.

this is the code part:

function findCommonDev(num1, num2) {
  var res = ((num1, num2) => {
    if (num1 > num2) {
      return num1;
    } else {
      return num2;
    }
  });
  console.log(res);
  }
  findCommonDev(10,12)

Now the questions arising from this are not related to the specific code.

  1. the console.log(res) prints '[function: res]' I would expect res to have the value of the bigger int passed to the function.

  2. I'm writing in VSC and the arguments are not marked as being used meaning that there is shadowing of num1 and num2 - why?

  3. how do I solve this elegantly?

Upvotes: 0

Views: 49

Answers (3)

Maheer Ali
Maheer Ali

Reputation: 36574

You need to called the function and pass num1 and num2 as parameters.

function findCommonDev(num1, num2) {
  var res = ((num1, num2) => {
    if (num1 > num2) {
      return num1;
    } else {
      return num2;
    }
  })(num1,num2);
  console.log(res);
}

findCommonDev(4,6)

Also notice that if you don't pass num1 and num2 the code won't work because inside the the function num1 and num2 are local variables and not the variables of outer function.

The expected arguments of function are just like local variables. They are created whether parameters are passed or not.

Upvotes: 3

StepUp
StepUp

Reputation: 38114

You are giving to console a function reference. However, of you want to run function, then specify parameters:

function findCommonDev(num1, num2) {
    var res = ((num1, num2) => {
      if (num1 > num2) {
        return num1;
      } else {
        return num2;
      }
    });
    return res(num1, num2);
    };


    console.log(findCommonDev(1,2));

Upvotes: 0

Nina Scholz
Nina Scholz

Reputation: 386604

Beside the returning of a new function (which is the real function for giving the wanted value), you could just take the max value.

function findCommonDev(num1, num2) {
    var res = Math.max(num1, num2);
    console.log(res);
}

findCommonDev(3, 42);

Upvotes: 1

Related Questions