Search code examples
javascriptfunctionarrow-functions

Difference between using arrow functions to declare method and function() when assigning the method to a variable?


If I have the following code:

let myObject = {
   greeting: "Hi",

   greet1(message) {
       return(console.log(`${this.greeting} ${message}`));
   },

   greet2() {
       return(message => console.log(`${this.greeting} ${message}`));
   }
}


greeting = "Hello";

anotherGreet1 = myObject.greet1;
anotherGreet1("It is sunny today");

anotherGreet2 = myObject.greet2(); // Why is there a parenthesis here?
anotherGreet2("It is raining today"); // Doesn't run unless previous line has ()

Why is it that when I assign anotherGreet1 with the function greet1 I don't need to use parentheses, but to assign greet2 to anotherGreet2 I need to use parenthesis? I understand that in assigning a function to a variable I want to assign the entire function and not just it's return value. This logic makes sense for greet1 but doesn't hold for greet2.


Solution

  • Your greet1 is function that first processes console.log(...) and only then returns it's value as string: myObject.greet1()

    Your greet2 if function that returns another function. You must call that function once more to be able to get output of console.log(...): myObject.greet2()()