Order of Code Execution

Say you run a JavaScript file with code that looks like this:

console.log("First!");
console.log("Second!");
    

Running this code will return exactly as you expect. You will see First! printed out, followed by Second!:

First!
Second!
    

In other words, JavaScript will evaluate your code left-to-right and top-to-bottom. Very intuitive! It's exactly how you are reading these notes right now.

However, when JavaScript sees a function definition, JavaScript will not evaluate the code inside the definition. It will execute the code inside the definition only when the function is invoked.

For example, consider a file with the code below:

console.log("First!");

function callMe() {
  console.log("Second!");
  console.log("Third!");
}

console.log("Fourth");
    

When you run this code, this will only print First! followed by Fourth!:

First!
Fourth!
    

To actually get the code within callMe to evaluate, you must call the callMe function by invoking it with parentheses (callMe()). The code below will now print based on the order of the console.log statements and the function invocation:

function callMe() {
  console.log("Second!");
  console.log("Third!");
}

console.log("First!");
callMe();
console.log("Fourth!");
    

Note: It's common to see and write functions with no parameters or arguments (no inputs).

Running this file will print these statements in this order:

First!
Second!
Third!
Fourth
    

Let's say JavaScript is running the file above. Here are the steps it would take, starting from the top of the file:

  1. JS sees a definition for the callMe function. It will remember this definition in case you call the function later. It will not evaluate the code inside the function yet.
  2. JS prints out "First!".
  3. JS sees that you are calling callMe(). At this point it will look at definition of the callMe function and run the code inside. As if you jumped inside the function definition, the console.log statements for printing "Second!" and "Third!" will execute.
  4. JS sees there is no more code to run inside of the callMe function, so it jumps back to where you originally invoked callMe().
  5. JS will continue evaluating in order and print "Fourth!".

Alternatively, you could invoke the callMe function after the console.log statements:

function callMe() {
  console.log("Second!");
  console.log("Third!");
}

console.log("First!");
console.log("Fourth!");
callMe();
    

Running this file will print these statements in this order:

First!
Fourth
Second!
Third!
    

Here are the steps running this file would take, starting from the top of the file:

  1. JS sees a definition for the callMe function.
  2. JS prints out "First!".
  3. JS prints out "Fourth!".
  4. JS sees that you are invoking the callMe function (callMe()). It will run the code inside the callMe function - this means it will execute the console.log statements to print "Second!" and "Third!".