0

I am studying JavaScript and I can't understand this.

function Out1()
{
    function In1()
        {
            console.log("text inside function In1");
        }
    return In1();
}


function Out2()
{
    return function In2()
        {
            console.log("text inside function In2");
        };
}

Out1();    // text inside function In1
Out2();    // 

Out2(); outputs nothing in console. What I am doing wrong?

2
  • 1
    Out2 returns an anonymous function which needs execution to produce your expected output. Out2()() would do that. Commented Mar 5, 2015 at 15:03
  • @LinusKleen: It's not anonymous. Commented Mar 5, 2015 at 15:05

1 Answer 1

1

Out2(); outputs nothing in console. What I am doing wrong?

Out2 returns a reference to the function it created. It doesn't call that function. You could call it by using () on the returned reference:

//  vv-------- These call `Out2`   
Out2()();
//    ^^------ These call the function referenced returned by `Out2`

E.g.:

var f = Out2(); // `f` is now a reference to the `In2` function
f();            // This calls `In2`
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks T.J Crowder. In fact, you answered 2 questions at once. First one was the title one, and the second one (I hope I am not wrong) the need of the () after the variable that makes a closure to obtain the return.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.