Reputation: 23
I have a question about Javascript Variable Declare. Could you please tell me what's the difference between the following two definition way? Why the alertMsg will be executed in the 1st way but not in the 2nd way? Thanks in advance.
//1
var alertMsgInvoker = alertMsg ('hi there');
function alertMsg (msg) {
alert(msg);
}
//2
var alertMsgInvoker = function () {
alertMsg ('hi there');
}
function alertMsg (msg) {
alert(msg);
}
Upvotes: 2
Views: 106
Reputation: 160211
You never call a function in the second example. You define some, but never call them.
In the first example you call alertMsg
when you define alertMsgInvoker
, in the second you define a function that calls alertMsg
--but call neither.
Upvotes: 3
Reputation: 2575
the first scenario, you are calling function alertMsg
which returns undefined.
var alertMsgInvoker = alertMsg ('hi there');
// assign the return value (undefined) to variable alertMsgInvoker
the second case, you just defined a variable alertMsgInvoker
, which is a function but never get called.
Upvotes: 1
Reputation: 915
In the first scenario you are calling the function alertMsg() with parameter "hi there"; The function is called which fires the alert-function. The function does not return anything, but still you bind the return value of the function to the variable alertMsgInvoker.
In the second scenario, you declare a function to the variabel alertMsgInvoker, then you declare a function named alertMsg. You never fire any of the functions here. That is why the second example doesn`t show the alert-box.
Upvotes: 1
Reputation: 45771
In your first example you're assigning the result of calling alertMsg ('hi there');
to the variable alertMsgInvoker
. The fact that alertMsg
doesn't return a value to put into alertMsgInvoker
is neither here nor there.
In the second example you're declaring alertMsgInvoker
is a function that, when called, calls the function alertMsg
. To obtain the same result as in your first example, your second would need to read:
var alertMsgInvoker = function () {
alertMsg ('hi there');
}
function alertMsg (msg) {
alert(msg);
}
// Now call alertMsgInvoker
alertMsgInvoker();
Upvotes: 3