-1

I want to understand the double return function in Javascript

I went through the other questions which was asked in SF regarding the return statement but I wasn't able to make sense out of it.

So, I was trying to understand HOC in react when I stumbled upon an article on medium.

The author wrote this line of code in his example.

const yell = (PassedComponent) =>
  ({ children, ...props }) =>
    <PassedComponent {...props}>
      {children.toUpperCase()}!
    </PassedComponent>

const Title = (props) => <h1>{props.children}</h1>

const AngryTitle = yell(Title)

<AngryTitle>Whatever</AngryTitle>

//=> <h1>WHATEVER!</h1>

Our HOC (Yell) here can also be return as

const yell = PassedComponent => ({children, ...props}) => {
    return (

Since there is two arrow function and something like this after first arrow function ({children, ...props}), I think it is double return HOC function.

[Question]: Can someone explain me double return or the code above?.

Alwaysblue
  • 9,948
  • 38
  • 121
  • 210
  • 3
    That's not really a double return. It's a function that returns another function. This would be **similar** [(_not exactly equivalent_)](https://stackoverflow.com/questions/32535110/what-are-the-differences-if-any-between-es6-arrow-functions-and-functions-boun) to `function yell(...){ return function(...){ return ...; } }` – blex May 20 '18 at 10:43
  • @blex either way, can you please explain the above question in details? – Alwaysblue May 20 '18 at 10:46

2 Answers2

1

First, to make things clearer, let's use the full syntax, by using curly braces and return statements:

const yell = (PassedComponent) => {
    return ({ children, ...props }) => {
        return (
            <PassedComponent {...props}>
                {children.toUpperCase()}!
            </PassedComponent>
        );
    };
}

Yes, the return word is used twice. But there are two functions here. And each one only has one return statement.

The outer one takes a component as parameter, and it returns a function. That function is now a component (yes, components are functions) that can be instanciated with children and props.

blex
  • 24,941
  • 5
  • 39
  • 72
0
const foo = arg1 => arg2 => arg1 + ar2;

Is a function that returns another function and is the same as:

function foo(arg1){
   return function(arg2){
     return arg1 + arg2
   }    
}

To get the inner return value you need to do

foo(input1)(input2)

Or variation where you store the returned function with an initial input and use it again

var f1 = foo(input1)
console.log(f1(input2))
console.log(f1(input3))
charlietfl
  • 170,828
  • 13
  • 121
  • 150