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.
It sounds like you incorrectly assume that the value displayed is also returned from the
alert()function. This is not so.alert()always returnsundefined. The first alert displays0, but0is not returned. Rather thealert()function returns the valueundefined. Since this is "falsey",alert(2)is also called which displays a2then returnsundefinedwhich is the final result of the||operator. Then this "undefined" is shown by the final alert.