Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

JavaScript JavaScript Foundations Variables Scope

Jose Agrelot
Jose Agrelot
13,416 Points

Nested Functions

When we have the nested function in this example why do we need to call the inner() function inside the the sayHello() function before we call the sayHello function outside of the code block?

Example:

function bam() {
    var part2 = "Treehouse";
    function boom() {
        var part3 = "Go ";
        console.log(part3 + part1 + part2);

    }

    boom();
}

bam();

Why do we have to call boom() first before bam() in order for the code to execute as expected? Is this a common practice when using a function with in a function?

1 Answer

Hugo Paz
Hugo Paz
15,622 Points

Hi Jose,

You don't explicitly call boom(). When you call bam(), boom() is run. boom() has access to bam() scope, this is how it gets part2 value.

The functions defined within another function won't be accessible outside the function unless they have been attached to an object that is accessible outside the function.