3.5 Q about Function Creation/Definition and Flow of Program

I have told the students that putting their function definitions at the end of the program is a convention for clean coding.

I am curious about how the computer processes the program so that this does not throw an error if the program first reads the call before the definition. I assumed it ran from top to bottom unless there is a conditional. Is a function a “condition” in that it tells the program to go look for the definition?

Thanks in advance. I hope this makes sense.

@mbrunner,
Javascript code when executed, is read from top to bottom and placed in a call stack. Variables declared at the top are placed in a global execution call stack where those items can be accessed by the whole program.They are then pushed to the top of the call stack. Functions are not executed until they are invoked / called. Once invoked, the function is moved the to the top of the call stack and executed. When the code within the invoked function is completed, the next invoked function is moved to the top of the call stack and then the next until the program is finished. For example:

var a = 'Hello Functions,';
console.log(a + ' This is the global call stack');
function one() {
  console.log('This is function one');
  two();
  console.log('This is still the first function');
}
function two() {
  console.log('This is the second function');
}
one();
console.log('This is also the global call stack');

When executed the output is displayed below:

Hello Functions, This is the global call stack
This is function one
This is the second function
This is still the first function
This is also the global call stack

Whenever conditionals are executed, they are run until the conditional code is complete. This happens whether the conditional is in the global call stack or inside a function. It is good practice to organize your code so that it can be understood by other coders. I hope this answers your question. Please let us know if further explanation is needed.

1 Like

What you want to research is Javascript hoisting.

A simple explanation is that variable and named functions are hoisted to the top of the file. Meaning it is as if var x or function f has been moved to the top.

Keep in mind if you use var x = 0; only the var x part is hoisted the x = 0 part remains where it is. So if you use x before the statement var x = 0; x will be a declared variable but have undefined as its value.

A named function is one where you write:
function f (x) {
An unnamed function is like the ones we use in onEvent:
onEvent("button","click",function () {

A named function is hoisted to the top along with its definition. That means that as you declare functions you can put them in any order and call them above the declaration in the file.

2 Likes

Thank you both!!! Watching the program run slowly and highlighting the code in App Lab was a helpful visual too.