As far I as know, code execution starts from top to bottom. In the following cases, why does alert()
function executes faster than line of codes found before it.
It's not that it's faster, though I can see how you got there, it's that it's synchronous.
alert
, confirm
, and prompt
are relics from the 1990s with little to no place in modern web programming¹. They bring the main UI and JavaScript thread to a screeching halt, show the dialog box, and wait for the user to do something.
Nothing else you can do from JavaScript can do that. The other things you do to display things modify the DOM, and those changes get drawn later, asynchronously, the next time the browser repaints the page.
In your event handler, you've changed the color of the element, but the browser hasn't had a chance to render that change yet, because the alert
has this anachronistic, synchronous stop-the-world behavior.
Note that different browsers handle these things differently. Some browsers may well show the element in red even when the alert
is showing. Others don't. Some may well show the console output in your first example; others don't.
In general, avoid alert
, confirm
, and prompt
in favor of using modern replacements — for this reason, because of the odd interactions they have with focus
/blur
events, because they cannot be styled, ...
Doing that (avoiding alert
, confirm
, and prompt
) got a lot easier in ES2018 with the addition of async
functions. And with a transpiler, you can use async
functions even if you need to target older browsers like IE11.
¹ And modern browsers are chipping away at support for them, for instance Chrome's behavior of not making alert
stop the code when the tab isn't active.