Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript calling function expression

Tags:

javascript

It makes sense by calling the function this way:

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

But why the following calling doesn't work?

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

What's the solution if we insist to use the format of "square = function (n)"?

like image 749
user1386284 Avatar asked May 29 '12 22:05

user1386284


People also ask

Why is a function call an expression in JavaScript?

A function call expression is used to execute a specified function with the provided arguments. If the function being called is overloaded, the compiler will attempt to match the argument types with the function parameter types. If there are no matching function declarations, a compile-time error will be raised.

Can you have an expression within a function call?

A function call is an expression containing the function name followed by the function call operator, () . If the function has been defined to receive parameters, the values that are to be sent into the function are listed inside the parentheses of the function call operator.

What does () => mean in JavaScript?

It's a new feature that introduced in ES6 and is called arrow function. The left part denotes the input of a function and the right part the output of that function.


1 Answers

"normal" function declarations are hoisted to the top of the scope, so they're always available.

Variable declarations are also hoisted, but the assignment doesn't happen until that particular line of code is executed.

So if you do var foo = function() { ... } you're creating the variable foo in the scope and it's initially undefined, and only later does that variable get assigned the anonymous function reference.

If "later" is after you tried to use it, the interpreter won't complain about an unknown variable (it does already exist, after all), but it will complain about you trying to call an undefined function reference.

like image 103
Alnitak Avatar answered Oct 20 '22 20:10

Alnitak