-2

How to call a function expression which being nested inside another function ?

   

 let a = function() {
 //do something
 let b = function() {
   console.log('Hello World!')  
 }
}
a();
NathanP
  • 49
  • 5

2 Answers2

2

See function expression:

Syntax

var myFunction = function [name]([param1[, param2[, ..., paramN]]]) { 
    statements
};

[...]

name The function name. Can be omitted, in which case the function is anonymous. The name is only local to the function body.

Note the last sentence.

why should i use variable to call a function and put parentheses after it?

You can define functions either as a function statement or as an expression. See var functionName = function() {} vs function functionName() {} for more information.

str
  • 33,096
  • 11
  • 88
  • 115
1

There are different ways to define functions in Javascript like Function declaration, Function expression and Arrow functions.

Function declaration can be defined as follow :

function a() { alert("a"); }

and you can call it by its name a()

and the second is function expression which can be defined in two ways:

//Anonymous Function Expression let anotherFn = function(){};

//Named function Expression let anotherFn = function b() {};

you can only call the above function as anotherFn()

In anonymous function expression, the function is assigned to a variable and that function can only be called by the variable name. An anonymous function expression doesn't have any name. However, you can also provide the name to the function expression. It is useful when you want to refer the current function inside the function body, e.g. in case of recursion. But the name is only accessible within the function body and can't be used to invoke the function outside. That's why you are getting error b is not defined.

shilpa syal
  • 46
  • 1
  • 5