Search code examples
javascriptscopelexical-scopelexical-closures

Javascript Lexical scope


I am trying to understand the concept of Lexical scope. As far as i know Lexical scope does not work backwards. In the below javascript code i have declared variable 'name' in scope3() function. But i tried to call it in scope1() and scope2() function. Since Lexical scope does not work backwards, I should have got "name is undefined" but it returns empty string. Can someone explain this?

var scope1 = function () {
  // name should have been undefined but its printing empty string
  console.log(name);
  var scope2 = function () {
    // name should have been undefined but its printing empty string
    console.log(name);
    var scope3 = function () {
      var name = 'Todd'; // locally scoped
    };
  };
  scope2();
};
scope1();


Solution

  • JavaScript has name built-in property. So, you'll get an empty string when you try to get name variable as it is pointing to window.name.

    You need to use something else instead of name.