If you are a C/C++ programmer, then you are not used to nesting functions. In JavaScript, you can have one function inside another. In this three-part series, I answer the following questions: can you call a nested function from outside the outermost function? Can a nested function call an outer function? What is the scope within nested functions? I will also show you how to pass arguments between nested functions and look at the relationship between nested functions and the JavaScript object.
Nesting JavaScript Functions - Calling the Functions from Outside (Page 3 of 5 )
You can call the outermost function from outside the set of functions. You cannot call any of the inner functions from outside the set of functions. The following code illustrates this:
The set of functions in the example is what we have in the code. There are three HTML buttons. When clicked, the first one will call the outermost function; when clicked, the second button should call the middle function (but it would fail); when clicked, the last button should call the innermost function (but it would fail).
Save the above code as an HTML file. Open it with your browser and click the buttons to confirm which functions are called. The inner functions will not be called; only the outer function will be called. This is the behavior of nested functions.
When the outermost function is called, by clicking its button, an alert box displays "Statements 1A." The nested functions cannot be called from outside the set of functions. When you click the second and third button to attempt this, the browser may indicate an error message at its status bar.