I am wondering Can you assign a variable to alert ? what does it really mean and do ? For example,
var a = alert('test');
I tried it out, and the alert pops up as soon as the page loads where variable a remains 'undefined' when I call it. Aren’t we suppose to make it an anonymous function with the alert inside like
var a = function(){ alert('test'); }
If we want to trigger an alert on something? Why does javascript allow you to do that?
Think of this statement like any other variable assignment. In order to perform the assignment, first the right-hand side is evaluated. In this case it’s a function call, so the function is called and its return value is obtained. In alert’s case, the return value is
undefined. It doesn’t return anything.Then the return value is assigned to
a, soaends up with the valueundefined.As a side effect of the statement, an alert message is displayed. That happens as a consequence of calling alert() and getting its return value.
This code is structurally similar to the alert call, and would result in
abeing 6. But then alert() doesn’t return a value. It’s more like this:Now
aisundefined.