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);
}
}
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);
}
}
xyz is an inner function which is private to abc function.
You cannot call xyz unless you make it public
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.
abc. It's however not in the global scope, somewhat obviously.onclickattributes 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.onclick="abc()();"to get it to run the returned function. You get two alerts though, so I'm not sure what this solves.