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

Alert only displays "Lilah" x3

I copied the example and ran it on the browsers' console but I'm getting a different result.

function greeting() { var person = 'Lilah'; alert(person); } var person = 'George'; greeting(); greeting(person); greeting();

When I run this on the browser's console it only shows three alert boxes with 'Lilah' and it never shows the variable 'George'.

2 Answers

Steven Parker
Steven Parker
243,656 Points

I think you might be missing the point.

It looks like this code is intended to demonstrate "scope rules", and since the function creates it's own variable named "person", it's entirely correct for it to display "Lilah" each time it is called. The variable created inside the function overrides the one created in the global scope.

Now just in case I have misinterpreted this exercise, post a link to the course page you are working with and I'll take another look.

Thank you for responding. Here's the link.

https://teamtreehouse.com/library/javascript-basics/creating-reusable-code-with-functions/variable-scope

I'm following the code that is mentioned and tried it on chrome's console but it only shows "Lilah".

Somehow I think I'm getting the point now.

I got it now. I followed the video and now I know where I got confused.

function greeting() { var person = 'Lilah'; alert(person); } var person = 'George'; greeting(); alert (person); greeting();

This is how I got it.

Steven Parker
Steven Parker
243,656 Points

Now that you shared the link, I can confirm that was the error. Good job spotting it yourself! :+1:

I was right, this is a scope demonstration, but as you discovered, you originally had written "greeting" where it should have been "alert".

You should put person as the argument not a variable.

function greeting (person){ alert(person); }

Thank you! I got it now.

Steven Parker
Steven Parker
243,656 Points

:x: That's not the function shown in the video.