Skip to the content.

Code 201 Class 10 Reading Notes

The Stack

The JavaScript interpreter processes one line of code at a time. When a sstatement needs data from another function, it stacks (or piles) the new function on top of the current task.

function greatUser() {
  return 'Hello ' + getName();
}
function getName() {
  var name = 'Molly';
  return name;
}
var greeting = greetUser();
alert(greeting);

1) The value for the greeting variable is obtained by calling the greetUser() function. So the variable cannot be assigned until the greetUser() function has done its job.

2) The statement is effectively put on hold, and the greetUser() task gets stacked on top of it. In turn, the greetUser() function cannot return a value until the getName() function has completed its task.

3) So, getName() is stacked on top of the greetUser() function. You can see the stack starting to build up. When getName() has done its job, a value is returned back to the greetUser() function.

4) Since getName() has done its job, it is removed from the stack. In turn, the greetUser() function can now finish its job and return a value to the greeting variable.

5) The greetUser() function has finished its work and it is removed from the stack and the value is finally assigned to the greeting variable.

<—BACK