DEdesigns57
DEdesigns57

Reputation: 361

Local and global scope of variables in JavaScript

I have tried reading other posts on the subject but no luck yet. In this code below why doesnt f2() have access to the var defined in f1(). Is not the var "name" a global to the function f2()? Should not f2() see the var "name"?

    function f1() {
     var name = "david";
     function f2() {
        document.writeln(name);
     }
     document.writeln(name);
  }                   

  f2(); // does not write out "david".

Upvotes: 0

Views: 243

Answers (3)

bits
bits

Reputation: 8340

You need to read up on Javascript Closures.

Here is a version of your snippet which demonstrates how you can access variables from outer function in an inner function (if you want to call inner function globally).

function f1()
{
   var name = "david";
   return function()
   {
      console.log(name);
   }
}
var f2 = f1();
f2();

Upvotes: 0

Ceres
Ceres

Reputation: 3648

Javascript is function level scoped, not block scoped. A function has access to it's parent's function variables but not to variables defined in functions within it. You could return f2 from f1 and call it that way

     function f1() {
         var name = "david";

         document.writeln(name);

         return f2

         function f2() {
            document.writeln(name);
         }

      } 

var f2 = f1();
f2();

Upvotes: 1

Matanya
Matanya

Reputation: 6346

your f2() is only defined inside f1() scope. you can't call it globally

Upvotes: 8

Related Questions