Logical operator AND/ OR short circus in Javascript

60 views Asked by At

Im still in very basic phase of JS,encountered a exercise I stucked recently, here's the code below:

alert(alert(0) || alert(2));

result return as 0 , then 2 and undefined

I understand how the OR work as looking for truthy value first, return the last value if none are found, but in code above, isn't it should stop evaluation after 2? Why the undefined return as well? It is falsy value.

1

There are 1 answers

0
Code-Apprentice On

result return as 0 , then 2 and undefined

It sounds like you incorrectly assume that the value displayed is also returned from the alert() function. This is not so. alert() always returns undefined. The first alert displays 0, but 0 is not returned. Rather the alert() function returns the value undefined. Since this is "falsey", alert(2) is also called which displays a 2 then returns undefined which is the final result of the || operator. Then this "undefined" is shown by the final alert.