-3

Can someone explain to me why the second function within the first function is undefined?

var a = 1

function abc () { 
    alert(a); 
        function xyz () { 
            alert(a); 
        } 
}

https://jsfiddle.net/kp950/yLs73cth/

6
  • 1
    You should include your HTML in your question here for it to make sense. Commented Mar 14, 2016 at 12:31
  • 1
    It's not undefined inside abc. It's however not in the global scope, somewhat obviously. Commented Mar 14, 2016 at 12:31
  • 1
    Regarding the dupe - inline event handlers in things like onclick attributes usually require their targets to be available within the global scope. It's also quite a dated technique - you should look into using event listeners, which allow you to arbitrarily nest functions and still have them respond to things like button clicks. Commented Mar 14, 2016 at 12:33
  • 1
    updated fiddle Commented Mar 14, 2016 at 12:35
  • 2
    @ozil "Uncaught TypeError: abc(...).xyz is not a function" - the alert you're seeing is the one from the outer function. You want onclick="abc()();" to get it to run the returned function. You get two alerts though, so I'm not sure what this solves. Commented Mar 14, 2016 at 12:36

2 Answers 2

1

xyz is an inner function which is private to abc function. You cannot call xyz unless you make it public

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

2 Comments

It seems like you can though by calling abc().xyz() jsfiddle.net/yLs73cth/4
@spex5 See my comments under the question related to that - xyz isn't actually running there, it's throwing an error. And @user2181397 said "unless you make it public". Returning the inner function from the outer one is making it public.
1

This is due to the scope at which you are trying to execute xyz() (globally). xyz() can only be run inside of abc() - where it is defined in the local scope.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.