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

Lexical scope?

var bar = "bar";

    function foo(str) {
        eval(str);
        console.log(bar); // 42
    }
    foo("var bar = 42;");

Yeah what? I'm pretty lost with this one.

2 Answers

Hey Jason,

Just taking a guess but I think you are confused why console.log(bar); returns 42 instead of 'bar'?

In the code you have a variable and function statement that gets attached to the Global Object ('window' in this case) when ran. Even though there is white space and indentation before your function statement, it still appears lexically in the Global Environment.

You have the function 'foo' that takes a string as a parameter that when called, will evaluate the string parameter that was passed to it, and call console.log(bar) after.

    function foo(str) {
        eval(str);
        console.log(bar); // 42
    }

Now when foo is called, with: foo("var bar = 42;"); the first thing it does is call the eval(str) function. And since the eval() function will evaluate a string if it represents an expression or statement, what we get back from eval(str); will be the expression or statement passed to it via the 'str' parameter. So really, what you get after it returns the result of eval() is :

    function foo(str) {
        var bar = 42; // !! Resulted from eval function call
        console.log(bar);
    }
    foo("var bar = 42;");

So now, since the resulting bar variable sits lexically inside the function and not the Global environment, the console.log(bar); code inside the function will now reference the new bar variable. Which is why you get the value of 42 in the console.log call.

For further clarification, you can still call console.log(bar) after and outside the function, and you will see that the bar variables don't collide since one is attached to the window object and the other is inside the function foo.

var bar = "bar";

      function foo(str) {
          var bar = 42; // !! Resulted from eval function call
          console.log(bar);
      }
      foo("var bar = 42;");
      console.log(bar); // This returns the string 'bar'

Hopefully this was what your question was lol

Thanks brother. :)