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);
}
In your first example you’re assigning the result of calling
alertMsg ('hi there');to the variablealertMsgInvoker. The fact thatalertMsgdoesn’t return a value to put intoalertMsgInvokeris neither here nor there.In the second example you’re declaring
alertMsgInvokeris a function that, when called, calls the functionalertMsg. To obtain the same result as in your first example, your second would need to read: