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

Michael Stopa
Michael Stopa
14,965 Points

No comprendo:(

Dear Friends, I do not quite understand which var/function gets precedence when invoked:

var part1 = "Team ";

function bam() { var part2 = "Treehouse"; console.log(part1); }

bam();

2 Answers

Jacob Miller
Jacob Miller
12,466 Points

Since the function bam only modifies the variable part2, the variable part1 is still "Team". Thus when you run bam(), it will change part2 to "Treehouse" and log "Team" to the console. Because part1 is in the global scope, the function can access it.

If part1 was defined inside a separate function, bam() would not be able to get it's value and log it to the console.

var part1 = "Team ";

function bam() {
    var part2 = "Treehouse";
    console.log(part1);
}

bam();
Michael Stopa
Michael Stopa
14,965 Points

Cool! Great thanks for the explanation.