1

I got a JavaScript error when running codes below:

<!DOCTYPE html>
<meta charset="utf-8">
<title>Untitled Document</title>
<script>
    var fn = function () {
        //var aaa = 'AAA';
        return function () {
            alert(aaa);
        };
    }();

    var foo2 = function () {
        var aaa = 'BBB';
        (function () {
            alert(aaa); // 'BBB'
        })();
        fn(); // Error: Uncaught ReferenceError: aaa is not defined
    }();
</script>

I think when fn function running, it should be able to find aaa in foo2 function.

But I got error. Why?

Thank you!

3 Answers 3

3

I think when fn function running, it should be able to find aaa in foo2 function.

No, it should not. aaa is declared in foo2 as a local variable, it is not accessible inside fn. What makes you think otherwise? No programming language I have seen would behave like that.

It will work if you uncomment the line //var aaa = 'AAA'; but then the alert inside fn will of course say "AAA" and not "BBB".

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

Comments

2

It doesn't work because aaa is out of fn()'s scope. What may be confusing you is that

(function () {
  alert(aaa); // 'BBB'
})();

Is working but fn() isn't. What's happening is that since "BBB" is defined and invoked inside foo2, alert(aaa) and aaa are in the same scope, and it works just fine.

Given that, you have two options:

  1. Declare aaa in a upper scope:

    var aaa = 'BBB';
    
    var fn = function () {
      return function () {
        alert(aaa);
      };
    };
    
    var foo2 = function () {
        (function () {
            alert(aaa); // 'BBB'
        })();
        fn();
    };
    
  2. Pass aaa as a parameter to fn():

    var fn = function (aaa) {
      return function () {
        alert(aaa);
      };
    };
    
    var foo2 = function () {
        var aaa = 'BBB';
        (function () {
            alert(aaa); // 'BBB'
        })();
        fn(aaa);
    };
    

Here's an article about javascript scoping:

http://www.digital-web.com/articles/scope_in_javascript/

I hope this helps.

Comments

1

You declared var aaa within foo2, so the scope of it is restricted to foo2. fn has no access to it.

Either declare var aaa outside of both functions, or pass it to fn as a parameter.

Comments

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.