Javascript call function expression

This makes sense by calling the function as follows:

print(square(5)); function square(n){return n*n} 

But why doesn't the next call work?

 print(square(5)); square = function (n) { return n * n; } 

What is the solution if we insist on using the format "square = function (n)"?

+4
source share
6 answers

"normal" function declarations go up to the top of the field, so they are always available.

Variable declarations are also raised, but assignment is not performed until a specific line of code is executed.

So, if you do var foo = function() { ... } , you create the variable foo in the scope, and it is initially undefined , and only later this variable gets the purpose of the anonymous function.

If "later" after you tried to use it, the interpreter will not complain about an unknown variable (in the end, it already exists), but it will complain that you are trying to call an undefined function reference.

+9
source

  var s=function () { console.log("hi there"); document.write("function express called"); alert("function express called"); } s(); 
 
+1
source

You need to change the order, you use the variable before its declaration and assignment:

 square = function (n) {//Better use "var" here to avoid polluting the outer scope return n * n; } print(square(5)); 

The correct way with var :

 var square = function (n) { // The variable is now internal to the function scope return n * n; } print(square(5)); 
0
source

In a function expression, you use the function, like any other value, if you expect:

 print(a); var a = 5 

work? (I do not ask)

0
source

In the second case, square is a regular variable to be (re) assigned. Consider:

 square = function (n) { return "sponge"; } print(square(5)); square = function (n) { return n * n; } 

What do you expect from the output here?

0
source

 var s=function () { console.log("s"); alert("function expression with anomious function"); } s(); var otherMethod=function () { console.log("s"); alert("function expression with function name"); } otherMethod(); 
0
source

Source: https://habr.com/ru/post/1415003/


All Articles