Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript assign variable to alert

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?

like image 296
peter Avatar asked Jan 23 '26 20:01

peter


2 Answers

var a = alert('test');

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, so a ends up with the value undefined.

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.

function foo(x) {
    return x * 2;
}

var a = foo(3);

This code is structurally similar to the alert call, and would result in a being 6. But then alert() doesn't return a value. It's more like this:

function bar(x) {
    return;
}

var a = bar(3);

Now a is undefined.

like image 73
John Kugelman Avatar answered Jan 26 '26 10:01

John Kugelman


var a = alert('test');  

This says to execute alert('test') and assign the return value from that function to a variable named a.

This would be no different than:

var max = Math.max(1,2,3,4);

where max would end up with the value 4 in it as the return value from executing Math.max(1,2,3,4).


var a = function(){ alert('test'); }

This says to declare an anonymous function and assign that function object to the variable a. Since the function is just declared, it is not executed at this time. You can execute it in the future with a().

like image 31
jfriend00 Avatar answered Jan 26 '26 11:01

jfriend00