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 Basics (Retired) Creating Reusable Code with Functions Variable Scope

John Haas
John Haas
1,756 Points

Scope question.

I get scope of variables for the most part, but had a question. What if you declare a variable inside a function and also declare the same variable outside? What happens to the variable? For example.

var name = "Tom";

function example() { var name = "Tom"; name = "Ed";
}

alert(name);

1 Answer

Ken Alger
STAFF
Ken Alger
Treehouse Teacher

John;

Welcome to Treehouse! Let's have a look, based on your code example:

var name = "Tom";

console.log("Initial name call outside of : ", name);

function example() {    
  var name = "Tom";
    console.log("Initial name call inside function: ", name);
  name = "Ed";
    console.log("Second name call inside function: ", name);
}

console.log("Second name call outside of function - before function is called: ", name);

example();

console.log("Third name call outside of function - after function is called: ", name);

That will output to the console log:

"Initial name call outside of : " "Tom" 
"Second name call outside of function - before function is called: " "Tom"
"Initial name call inside function: " "Tom"
"Second name call inside function: " "Ed"
"Third name call outside of function - after function is called: " "Tom"

As you can see during the function declaration, nothing is actually output until the function is called later in the code. For further information I would point you to the MDN Scope Cheatsheet.

Hope it helps and happy coding,

Ken