0

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".
1
  • Look in your error console. You should be seeing a message like "undefined is not a function". Commented Dec 14, 2012 at 18:56

3 Answers 3

8

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

Sign up to request clarification or add additional context in comments.

1 Comment

o okay got it. just added f2() in f1() and it works just like i thought. Thanks.
1

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();

1 Comment

While correct the initial sentence is orthogonal to the issue. Even if it were block-scoped, it would still behave the same. The error is because "functions are not magically put in the global scope"; a different topic. The rest goes on to show how it can be "exposed", but in a convoluted manner showing some other nuances .. be direct. Also, this will display "david" on the execution of f1 as well, which might not be desired.
0

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();

3 Comments

@Neal Well right, I can't say its correct. But I am guessing the intention of his code.
You guys have to realize that OP thinks that he can access the variable in outer function available to inner function. I simply pointed him to lookup on closures. And posted an example where one could do so. There is nothing wrong about my answer except my usage of word 'correct'. Which I will remove shortly.
o very interesting. having f1() return f2() basically. Then storing it in a variable and calling that var. Cool indeed thanks.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.