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)"?
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)"?
Share Improve this question edited May 29, 2012 at 22:09 gdoron 150k59 gold badges302 silver badges371 bronze badges asked May 29, 2012 at 22:03 user1386284user1386284 951 silver badge7 bronze badges 1 |6 Answers
Reset to default 12"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.
var s=function ()
{
console.log("hi there");
document.write("function express called");
alert("function express called");
}
s();
You need to change the order, you use the variable before it was declared and assigned:
square = function (n) {//Better use "var" here to avoid polluting the outer scope
return n * n;
}
print(square(5));
Correct way with var
:
var square = function (n) { // The variable is now internal to the function scope
return n * n;
}
print(square(5));
In function expression you are using the function like any other value, would you expect:
print(a);
var a = 5
to work? (I'm not really asking)
In the second case, square
is a regular variable subject to (re)assignment. Consider:
square = function (n) {
return "sponge";
}
print(square(5));
square = function (n) {
return n * n;
}
What would you expect the output to be here?
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();
foo = function () { alert('bar') }; foo(); foo = function () { alert('baz'};
the reasoning should become apparent. – zzzzBov Commented May 29, 2012 at 22:08