-2

I'm not familiar with this syntax to write a JS/ typescript function? Is there a name for this approach and I'm not exactly sure how it works or how it rewrites to a more obvious approach?

It looks like the method is calling this.updateMyField(param1, param2) but how is something1 and something2 handled?

Code snippet

const myMethod = (param1: string, param2: string) => this.updateMyField(
    something1,
    param1,
    param2,
    something2,
); 

"Standard" approach to writing a function

updateMyField = () => {
   // 
}

or..

updateMyField() {
   // 
}

Thank you

Jamie
  • 321
  • 1
  • 6
  • 18
  • It's called [arrow function](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions) –  Apr 30 '21 at 17:04
  • It isn't clear if you are asking about providing an expression instead of a block, or about parameters, or about types. – Quentin Apr 30 '21 at 17:05
  • thank you for the responses, I've added an extra paragraph to hopefully make the point I'm not clear on more obvious (?) – Jamie Apr 30 '21 at 17:07
  • @adiga When I wrote my comment there was only the first block in the question. The other two snippets came later. –  Apr 30 '21 at 17:07
  • 2
    `something1` and `something2` should be available in the same scope as `myMethod`. – adiga Apr 30 '21 at 17:07
  • Please provide a [mcve] and clarify what you're actually asking. –  Apr 30 '21 at 17:08
  • I assume so @adiga - my question is why or how something1 and something2 are omitted from the method declaration "(param1: string, param2: string)"? – Jamie Apr 30 '21 at 17:10
  • `something1` and `something2` probably are in the scope but without [mcve] we can't say for sure. –  Apr 30 '21 at 17:11
  • You don't need to pass that to `myMethod` because it already has access to those values (Assuming `something1` is available in the scope myMethod is created). You could pass it to `myMethod = (param1: string, param2: string, something1) => ..` if you want to create a pure function. It's not required. [How do JavaScript closures work?](https://stackoverflow.com/questions/111102) – adiga Apr 30 '21 at 17:12
  • Please check https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions and see if that helps – MRPie Apr 30 '21 at 17:41

1 Answers1

2

There's no special name for this.

A function has access to any variables in the scope it is declared in unless they are shadowed by local variables of the same name.

const example = 123;

const func = (param) => {
    console.log(example, param); 
};

func(456);
Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335