Im trying to call a nested function. Console error in Chrome dev tools says "f1 is not defined".
Whats wrong?
<!DOCTYPE html>
<html>
<body>
<h2>nested function test</h2>
<p>javascript nested functions</p>
<p id="demo"></p>
<script>
(function (f1){
(function (f2) {
function f3(c) {
return c + 2;
}
})
} )
let answer = f1.f2.f3(4);
document.getElementById("demo").innerHTML = "fred is " + answer
</script>
</body>
</html>
3
Answers
The compiler is correct. In this declaration:
f1
is an argument passed to an unnamed function. I suggest you review function declarations and scope. For this line to work:You could define an object within an object that has a function:
With Arrow Functions
With Normal JavaScript Functions
f1
andf2
are anonymous functions (functions without a name) so they can’t be called at all (at least the way you have them set up).Now, we don’t really nest functions within functions like you’ve done as the only way to execute named and nested functions would be to explicitly call each subsequent function from within its parent. Here’s one example:
Nested functions are generally used in the following two ways…
As a return value:
As methods of an object (and aside from the following example, we really don’t "nest" methods within the function declaration, we usually attach them to the function prototype and do so from outside of the function):