15

Is it possible to have a function within another function like so?

function foo() {

    // do something

    function bar() {

        // do something

    }

    bar();

}

foo();
1
  • 1
    @ gion_13: strictly speaking having a function within a function is not a "closure". The aspect that the function will preserve any variables in its scope even if they are not part of the function body itself (i.e. non-local variables) makes it a "closure". Commented Jul 21, 2011 at 22:40

3 Answers 3

20

Yes you can have it like that. bar won't be visible to anyone outside foo.

And you can call bar inside foo as:

function foo() {

    // do something

    function bar() {

        // do something

    }
    bar();

}
Sign up to request clarification or add additional context in comments.

2 Comments

I updated the code a little, is that still possible? Sorry for the stupid question.
:). Just added that to my answer. Yes you can.
6

Yes, you can.
Or you can do this,

function foo(){

    (function(){

        //do something here

    })()

}

Or this,

function foo(){

    var bar=function(){

        //do something here

    }

}

Or you want the function "bar" to be universal,

function foo(){

    window.bar=function(){

        //something here

    }

}

Hop this helps you.

Comments

4

That's called a nested function in Javascript. The inner function is private to the outer function, and also forms a closure. More details are available here.

Be particularly careful of variable name collisions, however. A variable in the outer function is visible to the inner function, but not vice versa.

3 Comments

Where exactly do I 'mean scope'?
"A variable in the outer function is visible to the inner function, but not vice versa." @Brennon
I see what you mean, but there's a reason I stated it that way. Because of the mechanics of the closure, I wanted to spell it out a bit more.

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.