Alwaysblue
Alwaysblue

Reputation: 11830

Function returning function

I was trying to wrap my head around the basics of JS

    const someFun = (name) => {
      return (name) => {
        console.log(name + 'yolo') 
        return name 
       }
    }

 const myName = someFun('Varun')
 console.log(myName)

This is returning (or logging)

(name) => {
   console.log(name + 'yolo') 
   return name 
  }

Whereases I was expecting it to log name passed as parameter (varun).

Can someone explain me why? and also why do we need a function return statement to have a function?

And lastly, I also see (say, in case of my redux) a code which looks like this

export const updateData = (updatedData) => {
  return function (dispatch) {

Here the main function takes updateData as a parameter but return function which takes dispatch as parameter (without any context in between). Can someone explain me this as well?

Upvotes: 0

Views: 140

Answers (1)

Quentin
Quentin

Reputation: 943142

Whereases I was expecting it to log name passed as parameter (varun).

someFun a function that returns a function. It doesn't do anything with the name argument at all.

If you called the returned function, then that would return the value of the name argument. (Note, that the returned function defines its own argumented named name, so that would make the one in someFun).

why do we need a function return statement to have a function?

You don't, but if you don't have a return statement, then the function will return undefined.

Here the main function takes updateData as a parameter but return function which takes dispatch as parameter (without any context in between). Can someone explain me this as well?

They use different variable names for their arguments. That's all.

This is useful as the nested function doesn't mask the outer function's variable so it can be accessed inside the nested function.

function updateData(updatedData) {
     return function (dispatch) {
         console.log({updatedData, dispatch});
     }
}

const returned_function = updateData(1);
returned_function(2);
returned_function(3);

Upvotes: 2

Related Questions