Search code examples
javascriptarrow-functions

Javascript Arrow calling a function from another with functionName() vs ()=>functionName


Let's say you have a method/function which you did not want to call until runtime.

const someMethod = () => {
  document.getElementById("myField").value = "Hello";
}

What is the term for and what is the difference between how these are executed.

this.check(() => someMethod);

AND

this.check(someMethod())

Solution

  • They're entirely different.

    this.check(() => someMethod); will pass a callback which, when called (if ever), returns a function.

    this.check(someMethod()) will call someMethod immediately, then pass the result to the this.check method.

    Another option not listed is this.check(() => someMethod());, which will call someMethod when the callback passed to check is called.

    If the this context is something you're worried about, then:

    this.check(someObj.someMethod)
    

    will result in someMethod, when invoked, to be invoked with a this of whatever the check method wants it to be. It does not preserve the context of someObj. In contrast

    this.check(() => someObj.someMethod())
    

    will result in someMethod being invoked with a this of someObj, regardless of how check tries to call it.

    So, usually, to be safe, you'll want this.check(() => someObj.someMethod()) - or bind someMethod in advance, or declare someMethod with an arrow function instead of a function.