0

In the following function, I return a function. This returned function tries to access 'arguments', but for some reason that references the outer function's 'arguments', not its own arguments. I know this is because it is an arrow function, so bound to the outer function, but don't feel satisfied that this is a good enough understanding. Could you explain why and also how to access the inner functions 'arguments'

function add() {
  let pa = arguments;
  if(arguments.length>1){
    return "regular function"
  }else{
    return ()=>{
      return "curried function with " + pa + " and " + arguments;
    }
  }
}

I know that returning a named hoisted function fixes this:

function add() {
  let pa = arguments;
  if(arguments.length>1){
    return "regular function"
  }else{
    return function curried(){
      return "curried function with " + pa + " and " + arguments;
    }
  }
}

I would still like a clearer way of thinking about the arrow function, and how to access local arguments in the arrow function.

Frazer Kirkman
  • 1,003
  • 1
  • 14
  • 23
  • 1
    Arrow functions do not have their own `arguments`. Either use a full-fledged `function`, like you're considering, or use argument rest syntax: `return (...args) => {` and then `args` will be an array containing the arguments for that function. Personally, I'd avoid using `arguments` when not necessary (it rarely is, rest syntax is nicer) – CertainPerformance Apr 18 '19 at 00:50
  • thank you. How did you know that arrow functions don't have 'arguments'? – Frazer Kirkman Apr 18 '19 at 01:53
  • 1
    You can look at the first answer in the linked question, or MDN: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions – CertainPerformance Apr 18 '19 at 01:53
  • also @CertainPerformance, I don't think this is a duplicate to the question you marked. If someone was having this issue, they wouldn't know that that question is what they needed. – Frazer Kirkman Apr 18 '19 at 01:54
  • Sure it is a duplicate - look at the first answer on the canonical question. See the `However, ES2015 introduces an alternative to using arguments: the rest parameter....` part – CertainPerformance Apr 18 '19 at 01:55
  • my point is that if someone had my issue, they wouldn't know to read that question and look closely at that first answer. – Frazer Kirkman Apr 18 '19 at 02:03

0 Answers0