Executing JavaScript
When a JavaScript execution environment, such as a node or a browser loads a JavaScript file, it parses it and then runs it. All the functions that are defined in a JavaScript file are registered, and all the code that is not in a function is executed. The order of the execution is according to the code's position in the file. So, consider a file having the following code:
console.log("First"); console.log("Second");
The console will always display this:
First Second
The order of the output cannot be changed, without changing the code itself. This is because the line with First
will be executed completely – always – and then, and only then, will the line with Second
begin to execute. This approach is synchronous because the execution is synchronized by the environment. We are guaranteed that the second line will not start executing, until and unless the line above it is completely done. But what happens if the...